/*
 * @Descripttion: 对话页面
 * @version:
 * @Author: linzhao
 * @Date: 2024-09-01 09:00:00
 */
Vue.component('dialogue-page', {
    template: '#chat-template',
    data() {
        return {
            isflageIOX: true,
            clipboard: {
                content: "",
            },

            inputPlaceholder: '请在此输入文字',

            //日程
            tripCheckResult: [],
            showTimeFlag: false,
            pickerKey: 0,
            selDate: new Date(),
            minDate: null,
            maxDate: null,
            currentTrip: null,
            oldTrips: [],
            showRemindTimePop: false,
            showTripTool: false,

            remindTimeCheck: true,
            remindTimes: [],
            remindTimeList: [{
                id: '0',
                value: 0,
                name: '准时'
            },{
                id: '1',
                value: 300,
                name: '5分钟前'
            },{
                id: '2',
                value: 900,
                name: '15分钟前'
            },{
                id: '3',
                value: 1800,
                name: '30分钟前'
            },{
                id: '4',
                value: 3600,
                name: '1小时前'
            },{
                id: '5',
                value: 7200,
                name: '2小时前'
            },{
                id: '6',
                value: 86400,
                name: '1天前'
            }],

            tripListPop: false,
            multiChoose: false,
            checkTripList: [],
            allTrips: [],
            allTripsLength: 0,
            chooseAll: false,
            
            //i国网录音相关
            voicelist: [],
            voiceTimer:null,
            isFlagStartTrue: false,

            //复制pop
            myCopyPopShow: true,
            myCopyPopItem: '',

            showQuery: false,
            showPPT: false,
            buttonShow: false,
            active: 0,
            showMajorPopover: false,
            showDeepSeekPop: false,
            deepSeekItem: {
                name: 'DeepSeek-V3',
                icon: './yr/images/chat-ds-sel.png',
                icon2: './yr/images/chat-ds-robot.png',
                value: 'V3',
            },
            deepSeekColor: '#506cfc',
            currentMajor: {},
            lightModelActions: [
                // {
                // name: '光明大模型A',
                // icon: './yr/images/chat-light-robot.png',
                // icon2: './yr/images/chat-a-robot.png',
                // unsave: true,
                // value: 'ALI'
                // }, {
                //     name: '光明大模型B',
                //     icon: './yr/images/chat-light-robot.png',
                //     icon2: './yr/images/chat-a-robot.png',
                //     unsave: true,
                //     value: 'BAIDU'
                // }
                {
                    name: 'DeepSeek-V3',
                    icon: './yr/images/chat-ds-sel.png',
                    icon2: './yr/images/chat-ds-robot.png',
                    value: 'V3',
                }, {
                    name: 'DeepSeek-R1',
                    icon: './yr/images/chat-ds-sel.png', 
                    icon2: './yr/images/chat-ds-robot.png',
                    value: 'R1',
                }
            ],
            tripModelActions: [{
                name: 'DeepSeek-V3',
                icon: './yr/images/chat-ds-sel.png',
                icon2: './yr/images/chat-ds-robot.png',
                value: 'V3',
            }],
            deepSeekActions: [{
                name: 'DeepSeek-V3',
                icon: './yr/images/chat-ds-sel.png',
                icon2: './yr/images/chat-ds-robot.png',
                value: 'V3',
            }, {
                name: 'DeepSeek-R1',
                icon: './yr/images/chat-ds-sel.png', 
                icon2: './yr/images/chat-ds-robot.png',
                value: 'R1',
            }
            // , {
            //     name: '光明大模型',
            //     icon: './yr/images/chat-light-robot.png',
            //     icon2: './yr/images/chat-a-robot.png',
            //     value: 'BAIDU'
            // }
            // , {
            //     name: '关闭',
            //     value: 'close'
            // }
        ],
            defaultModelActions: [{
                name: 'DeepSeek-V3',
                icon: './yr/images/chat-ds-sel.png',
                icon2: './yr/images/chat-ds-robot.png',
                value: 'V3',
            }, {
                name: 'DeepSeek-R1',
                icon: './yr/images/chat-ds-sel.png', 
                icon2: './yr/images/chat-ds-robot.png',
                value: 'R1',
            }
            // , {
            //     name: '光明大模型',
            //     icon: './yr/images/chat-light-robot.png',
            //     icon2: './yr/images/chat-a-robot.png',
            //     value: 'BAIDU'
            // }
            // , {
            //     name: '关闭',
            //     value: 'close'
            // }
        ],
            majors: [
            {
                'typeCode': '',
                'typeName': '全专业',
                'using': true
            },
            {
                'typeCode': 'yxbk',
                'typeName': '营销',
                'using': true
            },
            {
                'typeCode': 'CodeJiJian',
                'typeName': '基建',
                'using': true
            },
            {
                'typeCode': 'CodeWuziRole',
                'typeName': '物资',
                'using': true
            }, {
                'typeCode': 'CodeAuditNation,CodeAuditCompany',
                'typeName': '审计',
                'using': true
            }, {
                'typeCode': 'CodeLaws',
                'typeName': '法律',
                'using': true
            }, {
                'typeCode': 'BZZD_001_002,BZZD_001_003,BZZD_001_004,BZZD_001_006,BZZD_002_001,BZZD_002_002,DXJY_001_001,WXCG_003_001,ZCFG_001_001,ZCFG_001_002,ZCFG_003_001,ZCFG_003_002',
                'typeName': '发展',
                'using': true
            }
            ],
            noticeList: [
                {
                    id: "1",
                    content: "国网公司智慧办公包括哪些内容？",
                    icon: "./yr/images/chat-model.png",
                    questionType: "1"
                }, {
                    id: "2",
                    content: "数字化项目分为哪几类？",
                    icon: "./yr/images/chat-el.png",
                    questionType: "3"
                }, {
                    id: "3",
                    content: "近期有哪些热点新闻？",
                    icon: "./yr/images/chat-hot.png",
                    questionType: "2"
                }
            ],
            chatting: false,
            abortCtrl: null,

            chatRecords: [
                // {
                //     id: "1",
                //     content: "什么是人工智能什么是人工智能什么是人工智能什么是人工智能",
                //     contentHtml: "什么是人工智能什么是人工智能什么是人工智能什么是人工智能",
                //     type: 0,
                //     qfiles: [
                //         // { id: '1', name: '关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案.docx', type: 'WORD', fileSize: '120.3KB' },
                //         // { id: '2', name: '关于XXXXX的工作方案.docx', type: 'WORD', fileSize: '136.52KB' },
                //         // { id: '3', name: '关于XXX的工作方案.docx', type: 'WORD', fileSize: '120.3KB' },
                //         // { id: '4', name: '关于XXXXX的工作方案.docx', type: 'WORD', fileSize: '136.52KB' },
                //     ],
                // }, {
                //     id: "2",
                //     content: "1. 光大证\n2. 威风威风\n3.威风威风\n4. 没加哦加哦\n5. 哦i后i和",
                //     contentHtml: "1. 光大证\n2. 威风威风\n3.威风威风\n4. 没加哦加哦\n5. 哦i后i和",
                //     type: 1,
                //     // answerAttach: 22416,
                //     file: {
                //         // id: "11",
                //         // name: "AI技术融合与跨界发展AI技术融合与跨界发展AI技术融合与跨界发展AI技术融合与跨界发展.docx",
                //         // url: "",
                //         // type: "WORD",
                //         // fileSize: "121.62KB",
                //         // size: "121.62KB"
                //     }
                // },
                // }, {
                //     id: "1",
                //     content: "什么是人工智能什么是人工智能什么是人工智能什么是人工智能",
                //     type: 0,
                //     file: {
                //         id: "11",
                //         name: "AI技术融合与跨界发展.docx",
                //         url: "",
                //         type: "WORD",
                //         size: "121.62KB"
                //     }
                // }, {
                //     id: "2",
                //     content: "<h1>人工智能是</h1>XXXXX<br/>人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX",
                //     type: 1
                // }, {
                //     id: "1",
                //     content: "什么是人工智能什么是人工智能什么是人工智能什么是人工智能",
                //     type: 0,
                //     file: {
                //         id: "11",
                //         name: "AI技术融合与跨界发展.docx",
                //         url: "",
                //         type: "WORD",
                //         size: "121.62KB"
                //     }
                // }, {
                //     id: "2",
                //     content: "<h1>人工智能是</h1>XXXXX<br/>人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX人工智能是XXXXX",
                //     type: 1
                // }
            ],
            currentChatId: '',

            //-----------问题反馈
            feedBackPopShow: false,
            //当前选择的回答
            currentRecord: null,
            //修正答案
            feedSuggestion: '',
            //反馈类型列表
            feedBackTypeList: [{
                'value': '14',
                'name': '格式问题'
            },{
                'value': '13',
                'name': '逻辑问题'
            },{
                'value': '21',
                'name': '有害信息'
            },{
                'value': '11',
                'name': '事实错误'
            },{
                'value': '15',
                'name': '没有帮助'
            },{
                'value': '04',
                'name': '答非所问'
            }],
            feedBackSel: [],

            searchText: '',
            //1:大模型 2:热点新闻 3:专业问答 4:
            questionType: 1,
            //1.WORD转PDF 2.WORD转OFD 3.辅助阅读
            uploadIntent: 0,
            sendImg: './yr/images/no-send.png',
            fileList: [],
            uploadFileList: [
                // { id: '4043', name: '关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案关于XXX的工作方案.docx', type: 'WORD', fileSize: '120.3KB' },
                // { id: '4044', name: '关于XXXXX的工作方案.docx', type: 'WORD', fileSize: '136.52KB' },
                // { id: '3', name: '关于XXX的工作方案.docx', type: 'WORD', fileSize: '120.3KB' },
                // { id: '4', name: '关于XXXXX的工作方案.docx', type: 'WORD', fileSize: '136.52KB' },
            ],
            uploadFile: {
                // id: "4043",
                // name: "AI技术融合与跨界发展.docx",
                // type: "IMG",
                // size: "121.62KB"
            },
            showFile: false,
            showImg: false,
            uploadWord: false,
            progressBar: false,
            disabledInp: false,
            fileName: '',
            uploadTimer: null,
            uploading: false,
            uploadingFiles: [],
            // 设置每个分片的大小（字节）
            CHUNK_SIZE: 5 * 1024 * 1024 + "", // 1MB
            retryNum: 0,
            myindex: -1,
            fileSuffixs: ["doc", "docx", "pdf"], //["doc", "docx", "jpg", "jpeg", "png", "bmp", 'mp3', 'wav', 'pcm', 'amr', 'm4a', "MP3", "WAV", "PCM", "AMR", "M4A"],
            wordSuffixs: ["doc", "docx"],
            pdfSuffixs: ["pdf"],
            picSuffixs: ["jpg", "jpeg", "png", "bmp"],
            voiceSuffixs: ['mp3', 'wav', 'pcm', 'amr', 'm4a', "MP3", "WAV", "PCM", "AMR", "M4A"],
            voicing: false,
            voiceText: '',
            pressTimer: null,
            isPressing: false,
            buttonText: '松手发送，上移取消',
            movingUp: false,
            startY: 0,
            moveY: 0,

            showHistory: false,
            searchWidth: 24,
            isSearchFocused: false,
            searchParams: "",
            loading: false,
            finished: false,
            historyList: [
            ],
            //原始高度,用于Android软键盘弹出判断
            originalHeight: window.innerHeight,
            //播放地址
            videoSrc: "",
            isPlay: false,
            showSearch: false,
            audioItem: null,

            //流式输出显示控制
            chatTimer: null,
            chatBuffer: [],
            chatEnd: true,

            //语音
            MODEL_CODE: '1888',
            CAPACITY_CODE: '010115',
            LANG: 'zh',
            WS_URL: '',
            checkSwitch: false,
            VoiceItemID: generateUUID(),
            count: 0,
            checkClick: 1,
            bufferData: [],
            voiceTxt:{
                ind: '',
                old: ''
            },
            myWebsocket: null,
            nowTime: new Date().getTime(),

            touchTimer: null,
            popId: null,
            showCopyPopover: false,

            //语音播放
            isPlaying: false,
            audioSrc: '',

            //是否需要反馈提示
            feedBackTip: false
        }
    },
    watch: {
        uploadFileList: {
            handler: function(newValue, oldValue) {
                if(null != newValue && 0 < newValue.length){
                    this.showFile = true;
                    this.buttonShow = false;

                    this.uploadWord = true
                    this.uploadFileList.forEach(record => {
                        const suffix = record.name.split('.').reverse()[0]
                        if("doc" != suffix && "docx" != suffix) {
                            this.uploadWord = false
                        }
                    })
                } else {
                    this.uploadIntent = 0
                    this.showFile = false;
                    this.showImg = false
                    this.uploadWord = false
                    this.buttonShow = true;
                }

            },
            immediate: true // 立即执行监听
        },
        uploadIntent: {
            handler: function(newValue, oldValue) {
                if(0 == newValue){
                    this.searchText = ""
                }
            },
            immediate: true // 立即执行监听
        },
        searchText: {
            handler: function(newValue, oldValue) {
                if('' == newValue){
                    this.voiceText = ""
                }
            },
            immediate: true // 立即执行监听
        },
        questionType: {
            handler: function(newValue, oldValue) {
                if(3 != newValue){
                    this.currentMajor = {}
                }
            },
            immediate: true // 立即执行监听
        },
    },
    created() {
        this.createChat()
        const _this = this
        let jsApiList = []
        // $.getScript("../../../js/jweixin-sgccigw-1.0.0.js" /*"js/jweixin-1.0.0.js"*/, function () {
        //     'use strict';
        //     wx.ready(function () {
        //         wx.onHistoryBack(() => {
        //             _this.home()
        //             return false
        //         })
        //     });
        //     jsApiList = [
        //         'startRecord',
        //         'stopRecord',
        //         'onVoiceRecordEnd',
        //         'translateVoice',
        //         'previewFile',
        //         'onHistoryBack',
        //     ];
        //     wx.config({
        //         beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
        //         debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        //         appId: corpid,
        //         timestamp: '1626832073',
        //         nonceStr: nonceStr,
        //         signature: signature,
        //         jsApiList: jsApiList
        //     });
        // });
    },
    mounted() {
        this.compatibleInput()

        this.selectBtTypes()

        // this.queryChatQtype()

        this.addScrollEvent()

        // addPendingData(101, 4573)
        // setTimeout(() => {
        //     syncToast('同步失败同步失败同步失败同步失败同步失败', 300000000, "error")
        // }, 1000);
        // this.showAllTripPop()
        // this.addPopoverClick()
        // this.insertBtTypes()
        // this.updateBtTypes()
        // this.typeReset()
        // this.deleteBtTypes()

        // this.getMajorList()
        // this.getChatRecommend()
        // this.videoSrc = localUrlLink + iscp_port + `/tjAiAssistant/voice/display`;

        // this.testShowImg()
        // this.showFile = true
        // this.uploadWord = true
        // this.showImg = false
        // this.uploadFileList = [{
        //     id: 4574,
        //     type: "WORD",
        //     name: "关于召开启动会的会议通知.docx"
        // }]
        // this.questionType = 3
    },
    methods: {
        testShowImg() {
            this.uploadFileList = [
            {
                id: "4566",
                type: "IMG",
                name: "2025226_党建会议记录.docx",
                fileSize: 111 
            }
            // , {
            //     id: "4568",
            //     type: "IMG",
            //     name: "2025226_党建会议记录.docx",
            //     fileSize: 111 
            // }, 
            // {
            //     id: "4567",
            //     type: "IMG",
            //     name: "2025226_党建会议记录.docx",
            //     fileSize: 111 
            // }
            ]
            this.imageToBase64("4566", (imgSrc) => {
                this.$set(this.uploadFileList[0], 'imgSrc', imgSrc)
            })
            // this.imageToBase64("4568", (imgSrc) => {
            //     this.$set(this.uploadFileList[1], 'imgSrc', imgSrc)
            // })
            // this.imageToBase64("4567", (imgSrc) => {
            //     this.$set(this.uploadFileList[2], 'imgSrc', imgSrc)
            // })
            this.showFile = true
            this.showImg = true
            this.uploadWord = true
        },
        showUploadBtn() {
            if(this.isPressing) {
                return false;
            }
            if(5 == this.questionType) {
                return true
            }
            // if(4 != this.questionType) {
            //     return false
            // }
            if(this.deepSeekItem.value == 'ALI' || this.deepSeekItem.value == 'BAIDU') {
                return true
            }
            if(!this.uploadFileList || this.uploadFileList.length == 0) {
                return true
            }
            if(this.showImg && 1 == this.uploadFileList.length) {
                return false
            }
            return false
        },
        setupOutsideClickClose(element, callback) {
            function handleClickOutside(event) {
              if (null != element || !element || !element.contains(event.target)) {
                callback();
                document.removeEventListener('click', handleClickOutside);
              }
            }
            // 延迟绑定以避免立即触发
            setTimeout(() => {
              document.addEventListener('click', handleClickOutside);
            }, 0);
        },
        showChatTypePop(){
            if(this.showDeepSeekPop){
                return
            }
            this.showDeepSeekPop = true;
            setTimeout(() => {
                this.$nextTick(() => {
                    this.setupOutsideClickClose(document.getElementById('chatTypeDialog'), () => {
                        this.showDeepSeekPop = false;
                    })
                })
              }, 20);
        },
        handleFeedBackSelect(sel) {
            if(this.feedBackSel.includes(sel.value)) {
                //原来包含，则删除
                this.feedBackSel = this.feedBackSel.filter(item => item !== sel.value);
            }else {
                //原来不包含，则添加
                this.feedBackSel.push(sel.value)
            }
        },
        handleFeedBack(item, type) {
            if(item.feedType == type) {
                item.feedType = '0'
                item.feedReason = ''
                this.feedBack(item, type)
            }else if('1' == type){
                item.feedType = type
                item.feedReason = ''
                this.feedBack(item, type)
            }else if('-1' == type) {
                this.feedBackPopShow = true
                item.feedType = type
                this.currentRecord = item
                // this.feedBack(item, type)
            }
        },
        closeFeedBackPop() {
            this.feedBackSel = []
            this.feedSuggestion = ''
            
            this.feedBack(this.currentRecord)
        },
        submitFeedBack() {
            this.currentRecord.feedStatus = this.feedBackSel.join(',')
            this.currentRecord.feedSuggestion = this.feedSuggestion
            this.feedBackPopShow = false
            
            this.feedBackTip = true
        },
        feedBack(item) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": item.id,
                "feedType": item.feedType,
                "feedStatus": item.feedStatus,
                "feedSuggestion": item.feedSuggestion,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chat/feedBack",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            if('0' == item.feedType) {
                                mui.toast('已取消反馈', {
                                    duration: 1000,
                                    type: 'div'
                                })
                            }else if(this.feedBackTip || '1' == item.feedType){
                                mui.toast('感谢您的反馈', {
                                    duration: 1000,
                                    type: 'div'
                                })
                            }
                            
                        }
                    }
                    this.feedBackTip = false
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    this.feedBackTip = true
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        handleCopyPopOpend(item) {
            this.$nextTick(() => {
                this.myCopyPopItem = item
                let btb = document.getElementById('cpq2_' + item.id);
                let popover = btb.parentElement.parentElement;
                let left_px = this.copyPopLeft - 30
                popover.style.left = left_px + 'px'
                popover.style.top = this.copyPopTop + 'px'
                popover.style.display = 'block'
                btb.style.display = 'block'
                btb.parentElement.previousElementSibling.style.display = 'block'
            })
        },
        handleCopyPopOpend2(item) {
            this.$nextTick(() => {
                this.myCopyPopItem = item
                let btb = document.getElementById('cpq3_' + item.id);
                let popover = btb.parentElement.parentElement;
                let left_px = this.copyPopLeft - 30
                popover.style.left = left_px + 'px'
                popover.style.top = this.copyPopTop + 'px'
                popover.style.display = 'block'
                btb.style.display = 'block'
                btb.parentElement.previousElementSibling.style.display = 'block'
            })
        },
        handleTouchStart(event, item, id) {
            this.$set(item, 'showCopyPop', false)
            this.touchTimer = setTimeout(() => {
                if (navigator.vibrate) {
                    if(1 == item.type) {
                        let btb = document.getElementById('cpq2_' + item.id);
                        if(btb) {
                            btb.style.display = 'none'
                            btb.parentElement.previousElementSibling.style.display = 'none'
                        }
                        this.copyPopLeft = window.outerWidth/2
                        this.copyPopTop = event.touches[0].clientY
                        document.getElementById(id).style.transform = "scale(0.98)"
                    }else {
                        this.$set(item, 'showCopyPop', true)
                        event.target.style.transform = "scale(0.98)"
                    }
                    navigator.vibrate(200);
                } else {
                    console.log("当前设备不支持震动");
                }
                this.$set(item, 'showCopyPop', true)
            }, 500);
        },
        handleTouchStart2(event, item, id) {
            this.$set(item, 'showCopyPop2', false)
            this.touchTimer = setTimeout(() => {
                if (navigator.vibrate) {
                    if(1 == item.type) {
                        let btb = document.getElementById('cpq3_' + item.id);
                        if(btb) {
                            btb.style.display = 'none'
                            btb.parentElement.previousElementSibling.style.display = 'none'
                        }
                        this.copyPopLeft = window.outerWidth/2
                        this.copyPopTop = event.touches[0].clientY
                        document.getElementById(id).style.transform = "scale(0.98)"
                    }else {
                        event.target.style.transform = "scale(0.98)"
                    }
                    navigator.vibrate(200);
                } else {
                    console.log("当前设备不支持震动");
                }
                this.$set(item, 'showCopyPop2', true)
            }, 500);
        },
        handleTouchEnd(event, item, id) {
            this.touchTimer = clearTimeout(this.touchTimer)
            if(1 == item.type) {
                document.getElementById(id).style.transform = "scale(1)"
            }else {
                event.target.style.transform = "scale(1)"
            }
            console.log("长按结束")
        },
        mycopy(item, id) {
            // let content = item.reasoningContent ? (item.reasoningContent + item.content) : item.content
            let content = item.content
            if(1 == item.type) {
                content = ''
                let thinkDiv = document.getElementById('copyPop_' + item.id)
                if(thinkDiv) {
                    content += thinkDiv.innerText
                }
                let mainDiv = document.getElementById('copyPop2_' + item.id)
                if(mainDiv) {
                    content += mainDiv.innerText
                }
            }
            // console.log("复制内容", item.reasoningContent)
            // return
            if (content == '' || content.split(" ").join("").length == 0) {
              mui.toast('内容不能为空', {
                duration: 'long',
                type: 'div'
              })
              return
            }

            this.$nextTick(() => {
                var clipboard = new Clipboard('#'+id, {
                    // 通过target指定要复印的节点
                    text: function () {
                        return content
                    }
                });
                clipboard.on('success', (e) => {
                    this.$set(item, 'showCopyPop', false)
                    this.$set(item, 'showCopyPop2', false)
                    mui.toast('复制成功', {
                        duration: 'long',
                        type: 'div'
                    })
                });
                clipboard.on('error', (e) => {
                    mui.toast('复制失败', {
                        duration: 'long',
                        type: 'div'
                    })
                });
            })
        },
        //显示搜索框或者直接搜索
        searchShow(){
            this.showSearch = true;
            this.isSearchFocused = true;
        },
        //播放
        openPlay() {
            this.isPlay = true;
        },
        //获取专业问答列表
        getMajorList() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chat/getMajorList",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            //majors
                            // let datas = res.resultValue
                            // this.majors = []
                            // datas.forEach(data => {
                            //     this.majors.push({
                            //         id: data.typeCode,
                            //         text: data.typeName
                            //     })
                            // })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        getChatRecommend() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chatRecommend/queryList",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        this.noticeList = res.resultValue;
                    } else {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        delHistory(id) {
            var btnArray = ["取消", "确定"];
            var i = 0;
            mui.confirm("删除历史对话记录", "删除历史对话", btnArray, (e) => {
                if (i > 0) return;
                i++;
                if (e.index == 1) {
                    if (sessionStorage.getItem("iscp_port")) {
                        iscp_port = sessionStorage.getItem("iscp_port");
                    } else {
                        iscp_port = ""
                    }
                    let data = {
                        "id": id,
                        "timestamp": new Date().getTime() + "",
                    };
                    let AuthenticationSession = sessionStorage.getItem("Authentication");
                    data = JSON.stringify(data)
                    let sign = sm3(data);
                    $.ajax({
                        url: localUrlLink + iscp_port + "/tjAiAssistant/chat/delete",
                        type: "post",
                        async: false, //是否同步，false表示同步请求
                        dataType: "json",
                        data: data,
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8",
                            Authentication: AuthenticationSession,
                            sign: sign
                        },
                        success: (res, txt, xhr) => {
                            this.historyList = [];
                            this.historyCurrent = 1;
                            this.onLoadHistory();
                            if(this.currentChatId == id) {
                                this.currentChatId = generateUUID(32)
                                this.questionType = 1
                                this.chatRecords = []
                                this.nowTime = new Date().getTime()
                                this.stopChat()
                                if(this.$refs.audio) {
                                    this.$refs.audio.pause()
                                }
                                this.queryChatQtype()
                            }
                        },
                        error: (e) => {
                            $(".curtain").css("display", "none");
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        },
                    });
                } else {

                }
            });
        },
        deleteAllHistory() {
            var btnArray = ["取消", "确定"];
            var i = 0;
            mui.confirm("清空历史对话记录", "清空文件", btnArray, (e) => {
                if (i > 0) return;
                i++;
                if (e.index == 1) {
                    const userId = sessionStorage.getItem("userId");
                    if (sessionStorage.getItem("iscp_port")) {
                        iscp_port = sessionStorage.getItem("iscp_port");
                    } else {
                        iscp_port = ""
                    }
                    let data = {
                        "userId": userId,
                        "timestamp": new Date().getTime() + "",
                    };
                    let AuthenticationSession = sessionStorage.getItem("Authentication");
                    data = JSON.stringify(data)
                    let sign = sm3(data);
                    $.ajax({
                        url: localUrlLink + iscp_port + "/tjAiAssistant/chat/delete",
                        type: "post",
                        async: false, //是否同步，false表示同步请求
                        dataType: "json",
                        data: data,
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8",
                            Authentication: AuthenticationSession,
                            sign: sign
                        },
                        success: (res, txt, xhr) => {
                            this.historyList = [];
                            this.historyCurrent = 1;
                            this.onLoadHistory();

                            this.currentChatId = generateUUID(32)
                            this.questionType = 1
                            this.chatRecords = []
                            this.nowTime = new Date().getTime()
                            this.stopChat()
                            if(this.$refs.audio) {
                                this.$refs.audio.pause()
                            }
                            this.queryChatQtype()
                        },
                        error: (e) => {
                            $(".curtain").css("display", "none");
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        },
                    });
                } else {
                }
            });
        },
        onLoadHistory(searchType) {
            this.finished = false
            this.loading = true;
            const userId = sessionStorage.getItem("userId");
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            if (this.historyCurrent === 0) {
                this.historyCurrent = 1;
            }
            let data = {
                "userId": userId,
                "current": this.historyCurrent,
                "size": 20,
                "timestamp": new Date().getTime() + "",
            };
            if (searchType === 1) {
                data = {
                    "userId": userId,
                    "current": this.historyCurrent,
                    "question": this.searchParams,
                    "size": 20,
                    "timestamp": new Date().getTime() + "",
                };
            }

            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(data);
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chat/queryList",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    this.loading = false;
                    console.log("res", res);

                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            this.historytotal = res.resultValue.total
                            res.resultValue.list.forEach((item) => {
                                // 预计等待时间
                                this.historyList.push(item)
                            })
                            if (this.historytotal == 0) {
                                this.finished = true;
                            }
                            if (res.resultValue.list.length < 20) {
                                this.finished = true;
                            }
                            this.loading = false;
                            // if (this.historyList.length >= this.historytotal) {
                            //     this.finished = true;
                            // }
                            this.onCancel()
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        loadHistoryData() {
            if (!this.historyCurrent === 0) {
                this.finished = this.historyList.length >= this.historytotal;

            }
            if (!this.finished) {
                this.historyCurrent = this.historyCurrent + 1;
                this.onLoadHistory();
            }
        },
        backIndex() {
            this.showHistory = false;
        },
        handleFocus() {
            this.isSearchFocused = true;
            this.searchWidth = 20;
            console.log("isSearchFocused", this.isSearchFocused);
        },
        handleBlur() {
            this.isSearchFocused = false;
            this.searchWidth = 24;
            console.log("isSearchFocused", this.isSearchFocused);
        },
        onSearch() {
            this.historyList = [];
            this.historyCurrent = 1;
            this.onLoadHistory(1);
            this.searchParams = '';
        },
        onCancel() {
            this.searchParams = '';
            this.showSearch = false;
            this.isSearchFocused = false;
            this.searchWidth = 24;
        },
        openHistory() {
            this.showHistory = true;
            this.historyList = [];
            this.historyCurrent = 1;
            this.onLoadHistory();
        },

        toggleActive() {
            this.isActive = !this.isActive;
        },
        openQuery() {
            this.showQuery = true;

            console.log("showQuery", this.showQuery);

        },
        handleUploadIntentClick(type) {
            this.uploadIntent = this.uploadIntent == type ? 0 : type
            if(1 == this.uploadIntent) {
                this.searchText = "word转pdf"
            }else if(2 == this.uploadIntent) {
                this.searchText = "word转ofd"
            }else if(3 == this.uploadIntent) {
                this.searchText = "帮我总结这些文档"
            }else {
                this.searchText = ""
            }
            this.send()
        },
        handleMajorOpen() {
            this.$nextTick(() => {
                let popover = document.getElementsByClassName('van-popover')[0];
                let majorRow = document.getElementsByClassName('major-row')[0];
                let popoverContent = document.getElementsByClassName('van-popover__content')[0];
                popover.style.left = '0px'
                popover.style.width = '100%'
                majorRow.style.width = '100%'
                popoverContent.style.borderRadius = '0px'
                popover.style.display = 'block'
            })
        },
        handleMajorClosed() {
            let majorRow = document.getElementsByClassName('major-row')[0];
            majorRow.style.width = '0px'
            let popover = document.getElementsByClassName('van-popover')[0];
            popover.style.left = '0px'
            popover.style.width = '0px'
        },
        handleSelectMajor(item) {
            if(!item.using) {
                return
            }
            if(this.currentMajor && this.currentMajor.id == item.id) {
                this.currentMajor = {}
                this.questionType = 1
                this.queryChatQtype()
                return
            }
            // if(4 == this.questionType) {
            //     this.cancelChatQtype()
            // }
            this.questionType = 3
            this.currentMajor = item
            this.showMajorPopover = false
        },
        handleCancelMajor() {
            this.questionType = 1
            this.currentMajor = {}
            this.showMajorPopover = false
        },
        handleQuestionTypeClick(type) {
            if(3 == type) {
                //专业问答
                // this.questionType = type
                this.deepSeekActions = this.lightModelActions
                this.handleDeepSeekSelect(this.lightModelActions[0])
                this.showMajorPopover = true
                return
            }else if(4 == type) {
                this.showDeepSeekPop = true
                return
            }else if(this.questionType == type) {
                if(5 == type) {
                    this.searchText = ''
                }
                this.inputPlaceholder = '请在此输入文字'
                this.questionType = 1
                // this.deepSeekActions = this.defaultModelActions
                this.queryChatQtype()
            }else{
                // if(4 == this.questionType) {
                //     this.cancelChatQtype()
                // }
                if(2 == type) {
                    this.deepSeekActions = this.lightModelActions
                    this.handleDeepSeekSelect(this.lightModelActions[0])
                }else if(5 == type) {
                    this.deepSeekActions = this.tripModelActions
                    this.handleDeepSeekSelect(this.tripModelActions[0])
                    this.inputPlaceholder = '可为自己和他人创建日程'
                    this.showTripTool = true
                    // this.testShowImg()
                }
                this.questionType = type
            }
            this.currentMajor = {}
        },
        openPPt() {
            this.showPPT = true;
            console.log("showPPT", this.showPPT);

        },
        handleNoticeClick(item) {
            this.uploadFileList = []
            this.searchText = item.content
            this.questionType = 4 != this.questionType ? item.questionType : 4
            // this.cancelChatQtype()
            if('2' == item.questionType) {
                //热点新闻
            }else if('3' == item.questionType) {
                //专业问答
            }
            this.send()
        },
        imageToBase64(id, callback) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": id,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/common/downloadImg",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            if(callback) {
                                callback(res.resultValue)
                            }
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        getShowContent(item) {
            // console.log("回答内容", item.content)
            let reg = /(\!\[.*\])\((.*)\)/;

            this.$set(item, 'thinkEnd', true)

            //数学公式替换
            let reg2 = /\\\[([\s\S]*?)\\\]|\\\(([\s\S]*?)\\\)/g;
            // let reg2 = /\\\[([\s\S]*?)\\\]|\\\[.*?\\\]|\[.*?\]|\(.*?\)/g;
            let _content = item.content || ''
            let math_map = {}
            if(_content) {
                _content = _content.replace(/\r\n/g, '\n')
                _content = _content.replace(reg2, function(match, p1, p2) {
                    console.log("数学公式", match)
                    let mathId = generateUUID()
                    math_map[mathId] = match
                    return mathId
                });
            }

            if('DeepSeekR1' == item.modelType && 1 == item.type && 'R1' == item.secConfirmAnswerCode) {
                item.answerContent = ''
                let answer = _content
                this.$set(item, 'thinkEnd', false)
                //思考时间
                let think = item.bak ? JSON.parse(item.bak) : null
                if(think && think.thinkCost) {
                    this.$set(item, 'thinkCost', JSON.parse(item.bak).thinkCost)
                }

                if(think && think.reasoningContent) {
                    let thinkContent = think.reasoningContent
                    let thinkContents = []
                    if(thinkContent.replace(/\\n/g, "\n").trim('\\n','')) {
                        thinkContents = thinkContent.replace(/\\n/g, "\n").trim('\\n','').split('\n')
                    }
                    
                    this.$set(item, 'reasoningContent', think.reasoningContent)
                    this.$set(item, 'thinkContents', thinkContents)

                    if(answer) {
                        this.$set(item, 'thinkEnd', true)
                        item.answerContent = answer
                    }
                }else {
                    this.$set(item, 'thinkEnd', true)
                    item.answerContent = answer
                    // if(answer.indexOf('<think>') >= 0) {
                    //     let end = answer.length
                    //     let end2 = answer.length
                    //     if(answer.indexOf('</think>') >= 0) {
                    //         end = answer.indexOf('</think>')-7
                    //         end2 = answer.indexOf('</think>')
                    //         let content = answer.substr(answer.indexOf('</think>')+8)
                    //         item.answerContent += content
                    //         this.$set(item, 'thinkEnd', true)
                    //     }
                    //     let start = 0
                        
                    //     if(answer.indexOf('<think>') >= 0) {
                    //         start = answer.indexOf('<think>')+7
                    //     }
                    //     let thinkContent = answer.substr(start, end2-start)
                    //     let thinkContents = []
                    //     if(thinkContent.replace(/\\n/g, "\n").trim('\\n','')) {
                    //         thinkContents = thinkContent.replace(/\\n/g, "\n").trim('\\n','').split('\n')
                    //     }
                        
                    //     this.$set(item, 'thinkContents', thinkContents)
                    // }else {
                        
                    // }
                }
            }else {
                this.$set(item, 'thinkContents', null)
            }

            let newStr = _content
            if('articleImageGeneration' == item.chatIntent && item.answerAttach && 1 == item.type) {
                //文生图
                let userId = sessionStorage.getItem("userId");
                let Authentication = sessionStorage.getItem("Authentication");
                let timestamp = new Date().getTime()+"";
                let sign = sm3(timestamp + '&' + item.answerAttach)
                newStr = '![图片](' + localUrlLink + iscp_port + '/tjAiAssistant/common/download?id=' 
                    + item.answerAttach + '&userId=' + userId + '&timestamp=' + timestamp
                    + '&Authentication=' + Authentication + '&sign='+sign+')';

                this.imageToBase64(item.answerAttach, (imgSrc) => {
                    let img = '<img src="'+ imgSrc + '" alt="" />'
                    this.$set(item, 'contentHtml', img)
                })
                return
            }
            if('DeepSeekR1' == item.modelType && 1 == item.type && 'R1' == item.secConfirmAnswerCode) {
                newStr = item.answerContent
            }
            console.log(newStr)

            if(this.questionType == 2 || this.questionType == 3) {
                let reg2 = /(\n[\d]{1,}\.)[^\s].*/g;
                newStr = _content.replace(reg2, function(match, p1, p2) {
                    return match.replace(p1, p1+' ');
                });
            }

            var index = newStr.indexOf("<trip-end>");
            if(index >= 0) {
                newStr = newStr.substring(0, index);
            }
            // if(newStr.indexOf('\`\`\`markdown') >= 0) {
                // let md = newStr.replace(/\`\`\`markdown/g, '').replace(/\`\`\`/g, '').replace(/\\n/g, "\n").replace(/\n/g, "  \n")
                let md = newStr.replace(/\\n/g, "\n").replace(/\n/g, "  \n")
                newStr = marked.parse(md)

            // }

            
            let copy_ids = []
            let code_index = findAllIndexes(newStr, '<code class="language-')
            code_index.reverse().forEach(codeIndex => {
                let id = 'copy_' + generateUUID()
                copy_ids.push(id)
                
                let endIndex = newStr.substring(codeIndex+22).indexOf("\"")
                let code_type = newStr.substring(codeIndex+22, codeIndex+22+endIndex)

                newStr = newStr.substring(0,codeIndex) + '<div class="code-header"><div class="code-l">'+code_type+'</div><div id="'+id+'" class="code-r">复制代码</div></div>' + newStr.substring(codeIndex)
            })

            for(let key in math_map) {
                let s = math_map[key].replace('\r\n','').replace('\\\[', '').replace('\\\]', '')
                    .replace('\\\(', '').replace('\\\)', '')
                let mathHtml = katex.renderToString(s, { throwOnError: false });
                newStr = newStr.replace(key, mathHtml)
            }
            item['contentHtml'] = newStr

            this.$nextTick(() => {
                copy_ids.forEach(id => {
                    if(document.getElementById(id)) {
                        document.getElementById(id).addEventListener('click', (event) => {
                            event.preventDefault()
                            let text = event.target.parentElement.nextElementSibling.innerHTML
                            this.mycopy({'content': text}, id)
                        })
                    }
                })
            })

            // return newStr;
        },
        createChat() {
            this.showHistory = false
            this.currentChatId = generateUUID(32)
            this.questionType = 1
            this.chatRecords = []
            this.nowTime = new Date().getTime()
            this.stopChat()
            if(this.$refs.audio) {
                this.$refs.audio.pause()
            }
            this.queryChatQtype()
            this.handleReset()
        },
        stopChat() {
            if (this.abortCtrl) {
                this.abortCtrl.abort()
                if (this.chatRecords.length > 0) {
                    let chatRecord = this.chatRecords[this.chatRecords.length - 1]
                    this.$set(chatRecord, 'thinkEnd', true)
                    this.$set(chatRecord, 'showAudio', true)
                    if ('' == chatRecord['content'] && !chatRecord.reasoningContent) {
                        // chatRecord['content'] = ''
                        //如果内容为空则删除该数据
                        this.chatRecords.pop()
                    }else if(!chatRecord.firstSource){
                        chatRecord.sourceList = []
                        if(1 == chatRecord.questionType) {
                            chatRecord.firstSource = '光明大模型'
                        }else if(2 == chatRecord.questionType) {
                            chatRecord.firstSource = '互联网新闻'
                        }else if(3 == chatRecord.questionType) {
                            chatRecord.firstSource = '光明大模型'
                        }else if(4 == chatRecord.questionType && 'R1' == chatRecord.secConfirmAnswerCode) {
                            chatRecord.firstSource = 'DeepSeek-R1模型'
                        }else if(4 == chatRecord.questionType && 'V3' == chatRecord.secConfirmAnswerCode) {
                            chatRecord.firstSource = 'DeepSeek-V3模型'
                        }else if(6 == chatRecord.questionType) {
                            chatRecord.firstSource = '光明多模态大模型'
                        }
                    }
                }
            }

            // if(this.chatTimer) {
            //     this.chatTimer = clearIntervalTimer(this.chatTimer)
            // }
            this.chatting = false
            this.delFile()
            this.clickFunc('pause', this.audioItem)
        },
        reChat(item) {
            this.stopChat()

            this.$nextTick(() => {
                //重新发起会话
                let lastParam = this.chatRecords[this.chatRecords.length - 2]
                let qid = lastParam.id
                if(qid && qid.length > 32) {
                    qid = qid.substr(1)
                }
                let preParam = this.chatRecords[this.chatRecords.length - 1]
                let param = {
                    "id": qid,
                    "question": lastParam.content,
                    "questionType": lastParam.questionType,
                    "typeCode": preParam.secConfirmAnswerCode,
                    "userId": lastParam.userId,
                    "chatId": this.currentChatId,
                    "chatIntent": lastParam.chatIntent
                }
                if(lastParam.qfiles && lastParam.qfiles.length > 0) {
                    let questionAttach = lastParam.qfiles.map(file => file.id).join(",")
                    param.questionAttach = questionAttach
                }
                let oldAnswer = this.chatRecords[this.chatRecords.length - 1]
                oldAnswer.content = ''
                oldAnswer.contentHtml = ''
                oldAnswer.file = {}

                let typeCode = this.currentMajor.typeCode ? this.currentMajor.typeCode : ''
                if(4 == this.questionType) {
                    typeCode = this.deepSeekItem.value
                }
                param['typeCode'] = typeCode
                preParam.secConfirmAnswerCode = typeCode
                preParam.thinkContents = null
                preParam.firstSource = ''
                this.chatCall(param)
            })
        },
        handleSend() {
            this.send()
        },
        send(extraParam) {
            console.log("开始问答")

            this.showTripTool = false
            if ('' == this.searchText.trim()) {
                mui.toast("发送内容不可为空", { duration: "long", type: "div" });
                return;
            }
            let question = this.searchText.trim()
            //开始提问，置空
            this.searchText = ''
            let userId = sessionStorage.getItem("userId");

            let typeCode = this.currentMajor.typeCode ? this.currentMajor.typeCode : ''
            if(4 == this.questionType) {
                typeCode = this.deepSeekItem.value
            }
            let param = {
                "question": question,
                "questionType": !this.questionType ? 1 : this.questionType,
                "userId": userId,
                "typeCode": typeCode,
                "chatId": this.currentChatId
            }
            if(extraParam) {
                param = {...extraParam, ...param}
            }
            if(this.uploadFileList && 0 < this.uploadFileList.length) {
                param.questionAttach = this.uploadFileList.map(file => file.id).join(",")
            }

            //如果指定意图，使用指定意图
            if(1 == this.uploadIntent){
                param['chatIntent'] = "ptwPto"
            }else if(3 == this.uploadIntent) {
                param['chatIntent'] = "assistedReading"
            }else if (0 < this.chatRecords.length) {
                //上一条数据不为指定意图
                let oldChatRecord = this.chatRecords[this.chatRecords.length - 1]
                if("multiModelChat" == oldChatRecord['chatIntent']) {
                    param['chatIntent'] = "multiModelChat"
                }else if("tripRemind" == oldChatRecord['chatIntent'] && 0 == oldChatRecord['tripStatus']) {
                    param['chatIntent'] = "tripRemind"
                }else if("ptwPto" != oldChatRecord['chatIntent'] && "assistedReading" != oldChatRecord['chatIntent']) {
                    //取上一条数据的sessionId,chatIntent
                    // param['sessionId'] = oldChatRecord['oldChatRecord']
                    // param['chatIntent'] = oldChatRecord['chatIntent']
                    param['chatId'] = this.currentChatId
                }
            }

            //日程提醒
            if(5 == this.questionType) {
                param['chatIntent'] = "tripRemind"
            }
            //添加提问
            this.chatRecords.push({
                chatId: this.currentChatId,
                content: question,
                contentHtml: question,
                type: 0,
                userId: userId,
                questionType: !this.questionType ? 1 : this.questionType,
                typeCode: typeCode,
                // file: {...this.uploadFile},
                qfiles: this.uploadFileList,
                questionAttach: this.uploadFileList.map(file => file.id).join(","),
                chatIntent: param.chatIntent
            })

            let pModelType = getLargeModelType()
            if(!this.deepSeekItem) {
                pModelType = getLargeModelType()
            }else if('ALI' == this.deepSeekItem.value || 'BAIDU' == this.deepSeekItem.value) {
                pModelType = this.deepSeekItem.value
            }else if('R1' == this.deepSeekItem.value) {
                pModelType = 'DeepSeekR1'
            }else if('V3' == this.deepSeekItem.value) {
                pModelType = 'DeepSeekV3'
            }

            //添加答案
            this.chatRecords.push({
                chatId: this.currentChatId,
                content: '',
                contentHtml: '',
                type: 1,
                questionType: this.questionType,
                modelType: pModelType,
                typeCode: typeCode,
                firstSource: '',
                thinkEnd: true,
                showAudio: false,
                userId: userId
            })

            this.handleScrollBottom('scrollDiv')
            this.chatCall(param)
        },
        chatCall(param) {
            if(!this.deepSeekItem) {
                param['modelType'] = getLargeModelType()
            }else if('ALI' == this.deepSeekItem.value || 'BAIDU' == this.deepSeekItem.value) {
                param['modelType'] = this.deepSeekItem.value
            }else if('R1' == this.deepSeekItem.value) {
                param['modelType'] = 'DeepSeekR1'
                param['typeCode'] = this.deepSeekItem.value
            }else if('V3' == this.deepSeekItem.value) {
                param['modelType'] = 'DeepSeekV3'
                param['typeCode'] = this.deepSeekItem.value
            }else {
                param['modelType'] = getLargeModelType()
            }
            
            if(param['chatIntent'] == "ptwPto" || param['chatIntent'] == "assistedReading") {
                if('ALI' == param['modelType']) {
                    param['modelType'] = "BAIDU"
                }
            }

            //在这里操作流式数据,最后一条
            let newChatRecord = this.chatRecords[this.chatRecords.length - 1]
            let qChatRecord = this.chatRecords[this.chatRecords.length - 2]
            newChatRecord['modelType'] = param['modelType']
            newChatRecord['secConfirmAnswerCode'] = param['typeCode']

            console.log('会话参数是:', JSON.stringify(param))

            // param['question'] = encodeURIComponent(param['question'])
            // let base64Str = Base64.encode(param['question']);
            param['question'] = sm2.doEncrypt(param['question'], sessionStorage.getItem("bpuk"), 1)
            // param['question'] = Base64.encode(param['question']);
            if (typeof (EventSource) !== "undefined") {
                console.log("SSE supported in this browser.");
            } else {
                console.log("SSE not supported in this browser.");
            }
            this.chatting = true
            this.chatBuffer = []
            this.delFile()
            newChatRecord['showAudio'] = false
            this.clickFunc('pause', this.audioItem)

            // param['chatIntent'] = 'tripRemind'
            // param['questionAttach'] = '4541'
            // this.abortCtrl = streamChat('http://172.20.10.5:14800/tjAiAssistant/chat/chat', param,
            this.abortCtrl = streamChat(localUrlLink + iscp_port + '/tjAiAssistant/chat/chat', param,
                (res) => {
                    // ca += res.resultValue.answer
                    console.log("会话返回内容", res.resultValue)
                    let succesStatus = res.successful
                    if(!succesStatus){
                        //返回异常，直接结束
                        console.log('返回异常，结束会话')
                        var content = res['resultValue']
                        newChatRecord['content'] += content
                        newChatRecord['contentHtml'] = content
                        this.stopChat()
                        return ;
                    }
                    // this.delFile()
                    var ansData = res['resultValue']
                    var content = ansData['answer']
                    this.currentChatId = ansData['chatId']

                    //为问题数据增加id
                    qChatRecord['id'] = ansData['id']
                    newChatRecord['id'] = ansData['id']
                    newChatRecord['questionType'] = ansData['questionType']
                    newChatRecord['question'] = ansData['question']
                    newChatRecord['questionAttach'] = ansData['questionAttach']
                    // newChatRecord['pptType'] = ansData['pptType']
                    newChatRecord['answerAttach'] = ansData['answerAttach']
                    newChatRecord['chatId'] = ansData['chatId']
                    newChatRecord['sessionId'] = ansData['sessionId']
                    newChatRecord['chatIntent'] = ansData['chatIntent']
                    newChatRecord['bak'] = ansData['bak']
                    newChatRecord['secConfirmAnswerCode'] = ansData['secConfirmAnswerCode']
                    this.$set(newChatRecord, 'feedType', '0')
                    newChatRecord['content'] += content

                    newChatRecord['thinkEnd'] = true
                    newChatRecord['modelType'] = ansData['modelType']

                    //日程字段
                    newChatRecord['tripId'] = ansData['tripId']
                    newChatRecord['tripStatus'] = ansData['tripStatus']

                    // if('<think>' == content) {
                        this.$set(newChatRecord, 'thinkShow', true)
                    // }
                    this.getShowContent(newChatRecord)
                    // newChatRecord['contentHtml'] = this.getShowContent(newChatRecord)

                    //带附件
                    if(ansData['answerAttach'] && ansData.bak) {
                        newChatRecord['content'] = ' '
                        let _file = JSON.parse(ansData.bak)
                        newChatRecord.file = {
                            id: _file.id,
                            name: _file.name,
                            type: _file.type,
                            size: _file.size,
                            fileSize: calcFileSize(_file.size)
                        }
                        // newChatRecord.file.type = newChatRecord.file.type.toUpperCase()
                        // newChatRecord.file.fileSize = this.calcFileSize(newChatRecord.file.size)
                        console.log(newChatRecord['file'])
                    }

                    //日程错误信息显示
                    if(ansData['bak']) {
                        var bak = JSON.parse(ansData['bak'])
                        if(bak.tripErrMsg) {
                            this.$set(newChatRecord, 'tripErrMsg', bak.tripErrMsg)
                        }
                        if(bak.imgTrips) {
                            this.$set(newChatRecord, 'editable', false)
                            let trips = bak.imgTrips
                            trips.forEach(trip => {
                                this.$set(trip, 'check', false)
                                this.$set(trip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                                //如果当天，显示今天 hh:mm
                                if(dateFormat('yyyy-MM-dd', trip.tripTime) == dateFormat('yyyy-MM-dd', new Date())) {
                                    this.$set(trip, 'tripTimeShow', dateFormat('今天 hh:mm', trip.tripTime))
                                }else{
                                    this.$set(trip, 'tripTimeShow', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                                }
                            })
                            this.$set(newChatRecord, 'trips', trips)
                        }
                    }

                    this.$set(newChatRecord, 'tripStatus', ansData['tripStatus'])
                    let trips = ansData['trips']
                    if(trips) {
                        this.$set(newChatRecord, 'editable', false)
                        trips.forEach(trip => {
                            this.$set(trip, 'check', false)
                            this.$set(trip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                            //如果当天，显示今天 hh:mm
                            if(dateFormat('yyyy-MM-dd', trip.tripTime) == dateFormat('yyyy-MM-dd', new Date())) {
                                this.$set(trip, 'tripTimeShow', dateFormat('今天 hh:mm', trip.tripTime))
                            }else{
                                this.$set(trip, 'tripTimeShow', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                            }
                        })
                        this.$set(newChatRecord, 'trips', trips)
                    }

                    // console.log("显示内容", newChatRecord['content'])
                    if (ansData['isEnd']) {
                        console.log("完成")
                        newChatRecord.sourceList = []
                        newChatRecord.firstSource = ''
                        this.$set(newChatRecord, 'showSourceMore', false)
                        if(1 == newChatRecord.questionType) {
                            newChatRecord.firstSource = '光明大模型'
                        }else if(2 == newChatRecord.questionType) {
                            newChatRecord.firstSource = '互联网新闻'
                        }else if(3 == newChatRecord.questionType && ansData.bak) {
                            let bak = JSON.parse(ansData.bak)
                            let source = bak.source
                            if(source && source.length > 0) {
                                newChatRecord.firstSource = source[0]
                                if(source.length > 1) {
                                    for(var i=1;i<source.length;i++) {
                                        newChatRecord.sourceList.push({
                                            'name': source[i]
                                        })
                                    }
                                }
                            }else {
                                newChatRecord.firstSource = '光明大模型'
                            }
                        }else if(4 == newChatRecord.questionType && 'R1' == newChatRecord.secConfirmAnswerCode) {
                            newChatRecord.firstSource = 'DeepSeek-R1模型'
                        }else if(4 == newChatRecord.questionType && 'V3' == newChatRecord.secConfirmAnswerCode) {
                            newChatRecord.firstSource = 'DeepSeek-V3模型'
                        }else if(5 == newChatRecord.questionType) {
                            newChatRecord.firstSource = 'DeepSeek-V3模型'
                        }else if(6 == newChatRecord.questionType) {
                            newChatRecord.firstSource = '光明多模态大模型'
                        }else {
                            newChatRecord.firstSource = '光明大模型'
                        }
                        console.log("请求完成")
                        newChatRecord['showAudio'] = true
                        this.$set(newChatRecord, 'showAudio', true)
                        this.stopChat()
                    }
                    
                    this.handleScrollBottom('scrollDiv')
                }, (err) => {
                    //失败回调
                    console.log("----------------对话异常-------------", err)
                    let newChatRecord = this.chatRecords[this.chatRecords.length - 1]
                    //返回异常，直接结束
                    console.log('对话异常', err)
                    var content = '对话异常'
                    newChatRecord['content'] += content
                    newChatRecord['contentHtml'] = content
                    // mui.toast("对话异常", { duration: "long", type: "div" });
                    this.stopChat()
                    // this.abortCtrl.abort()
                    // 直接抛出错误，避免反复调用
                    throw err
                }, e => {
                    newChatRecord['showAudio'] = true
                    this.$set(newChatRecord, 'showAudio', true)
                    //请求完成
                    console.log("对话结束")
                    this.stopChat()
                });
        },
        openHistoryRecord(id) {
            this.handleReset()
            this.myCopyPopShow = true
            this.stopChat()
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            let userId = sessionStorage.getItem("userId");
            let data = {
                "chatId": id,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(data)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chatRecord/selectByChatId",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    this.chatRecords = res.resultValue;
                    this.chatRecords.forEach((item, index) => {
                        this.currentChatId = item.chatId
                        this.$set(item, 'thinkShow', true)
                        this.getShowContent(item)

                        if(null != item.tripStatus && 1 != item.tripStatus) {
                            this.$set(item, 'chatIntent', 'tripRemind')
                        }
                        if(index == this.chatRecords.length-1) {
                            this.$set(item, 'showAudio', true)
                        }
                        if(item.qfiles) {
                            item.qfiles.forEach(qfile => {
                                console.log('qfile', qfile)
                                if('IMG' == qfile.type) {
                                    this.$set(qfile, 'imgShow', true)
                                        //   let Authentication = sessionStorage.getItem("Authentication");
                                        //   let timestamp2 = new Date().getTime()+"";
                                        //   let sign2 = sm3(timestamp2 + '&' + qfile.id)
                                        //   let userId = sessionStorage.getItem("userId");
                                        //   let ans = '/tjAiAssistant/common/download?id=' + qfile.id + '&userId=' + userId + '&timestamp=' + timestamp2 + '&Authentication=' + Authentication + '&sign='+sign2
                                        // this.$set(item, 'contentHtml', ans)
                                        // this.$set(item, 'content', ans)
                                    this.imageToBase64(qfile.id, (imgSrc) => {
                                        this.$set(qfile, 'imgSrc', imgSrc)
                                    })
                                }
                            })
                        }
                        if(item.trips) {
                            this.$set(item, 'editable', false)
                            item.trips.forEach(trip => {
                                this.$set(trip, 'check', false)
                                //如果当天，显示今天 hh:mm
                                if(dateFormat('yyyy-MM-dd', trip.tripTime) == dateFormat('yyyy-MM-dd', new Date())) {
                                    this.$set(trip, 'tripTimeShow', dateFormat('今天 hh:mm', trip.tripTime))
                                }else{
                                    this.$set(trip, 'tripTimeShow', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                                }
                                this.$set(trip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                            })
                            // this.$set(item, 'trips', item.trips)
                        }

                        //日程错误信息显示
                        if(item.bak) {
                            var bak = JSON.parse(item.bak)
                            item.tripErrMsg = bak.tripErrMsg
                            if(bak.imgTrips) {
                                this.$set(item, 'editable', false)
                                let trips = bak.imgTrips
                                trips.forEach(trip => {
                                    this.$set(trip, 'check', false)
                                    this.$set(trip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                                })
                                this.$set(item, 'trips', trips)
                            }
                        }

                        // item['contentHtml'] = this.getShowContent(item)
                        this.$set(item, 'showCopyPop', false)
                        if(1 == item.type) {

                            item.sourceList = []
                            item.firstSource = ''
                            this.$set(item, 'showSourceMore', false)
                            this.$set(item, 'thinkEnd', true)
                            // item.showSourceMore = false
                            if(1 == item.questionType) {
                                item.firstSource = '光明大模型'
                            }else if(2 == item.questionType) {
                                item.firstSource = '互联网新闻'
                            }else if(3 == item.questionType) {
                                let source = item.sources
                                if(source && source.length > 0) {
                                    item.firstSource = source[0]
                                    if(source.length > 1) {
                                        for(var i=1;i<source.length;i++) {
                                            item.sourceList.push({
                                                'name': source[i]
                                            })
                                        }
                                    }
                                }else {
                                    item.firstSource = '光明大模型'
                                }
                                console.log(item.firstSource)
                            }else if(4 == item.questionType && 'R1' == item.secConfirmAnswerCode) {
                                item.firstSource = 'DeepSeek-R1模型'
                            }else if(4 == item.questionType && 'V3' == item.secConfirmAnswerCode) {
                                item.firstSource = 'DeepSeek-V3模型'
                            }else if(5 == item.questionType) {
                                item.firstSource = 'DeepSeek-V3模型'
                            }else if(6 == item.questionType) {
                                item.firstSource = '光明多模态大模型'
                            }else {
                                item.firstSource = '光明大模型'
                            }
                        }
                        // item['showCopyPop'] = false
                    })
                    console.log(this.chatRecords)
                    this.showHistory = false;
                    this.resetMainHeight()
                    this.handleScrollBottom('scrollDiv')
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        handleMoreSource(item) {
            this.$set(item, 'showSourceMore', !item.showSourceMore)
        },
        handleScrollBottom(refName) {
            this.$nextTick(() => {
                // let scrollElem = this.$refs.scrollDiv;
                let scrollElem = this.$refs[refName];
                if(scrollElem) {
                    console.log('scrollElem', $(scrollElem).prop('scrollHeight'))
                    $(scrollElem).stop(true, true)
                    $(scrollElem).animate({ scrollTop: $(scrollElem).prop('scrollHeight')},5)
                }
            })
        },
        addScrollEvent() {
            this.$nextTick(() => {
                let scrollElem = this.$refs['scrollDiv'];
                if(scrollElem) {
                    scrollElem.addEventListener('scroll', (e) => {
                        if(this.myCopyPopItem) {
                            if(this.myCopyPopItem.showCopyPop) {
                                this.$set(this.myCopyPopItem, 'showCopyPop', false)
                                let btb = document.getElementById('cpq2_' + this.myCopyPopItem.id);
                                if(btb) {
                                    btb.parentElement.previousElementSibling.style.display = 'none'
                                    btb.style.display = 'none'
                                    
                                }
                            }else if(this.myCopyPopItem.showCopyPop2) {
                                this.$set(this.myCopyPopItem, 'showCopyPop2', false)
                                let btb = document.getElementById('cpq3_' + this.myCopyPopItem.id);
                                if(btb) {
                                    btb.parentElement.previousElementSibling.style.display = 'none'
                                    btb.style.display = 'none'
                                }
                            }
                        }
                    })
                }
            })
        },
        // 判断安卓还是ios
        compatibleInput() {
            //获取浏览器的userAgent,并转化为小写
            var ua = navigator.userAgent.toLowerCase();
            //判断是否是苹果手机，是则是true
            var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
            if (isIos) {
                this.isflageIOX = true;
                // iOS系统
                console.log('ios')
                window.addEventListener('focusin', this.onFocusin);
                window.addEventListener('focusout', this.onFocusout);
            } else {
                this.isflageIOX = false;
                // Android软键盘监听
                console.log('Android')
                window.addEventListener('resize', this.onResize);
            }
        },
        onFocusin(){ //iOS系统:软键盘弹出
            // this.buttonShow = false;
            this.showFile = false;
            this.resetMainHeight()
        },
        onFocusout(){ //iOS系统:软键盘收起
            if(this.uploadFileList && 0 < this.uploadFileList.length){
                this.showFile = true;
            } else {
                this.buttonShow = true;
            }
            this.resetMainHeight()
        },
        onResize(){
            const resizeHeight = window.innerHeight;
            console.log('原始高度', this.originalHeight)
            console.log('resizeHeight', resizeHeight)
            if (this.originalHeight - resizeHeight > 50) {
                // 'Android系统: 软键盘弹出'
                console.log('弹出')
                // this.buttonShow = false;
                this.showFile = false;
            } else {
                // 'Android系统: 软键盘收起'
                console.log('收起')
                if(this.uploadFileList && 0 < this.uploadFileList.length){
                    this.showFile = true;
                } else {
                    this.buttonShow = true;
                }
            }
            this.resetMainHeight()
        },
        home() {
            if(this.tripListPop) {
                this.closeTripListPop()
            }
            if (!isFlag) {
                closeIscp();
            }
            IscLogout()
            wx.closeWindow();
            // $(location).attr("href", "../../Home.html");
        },
        //关闭播放
        closePlay(){
            this.isPlay = false
        },
        createSgin(data) {
            let hashData = sm3(data);
            let hashData_last = sm3(hashData);
            hashData_last = hashData_last.substr(0, 5);
            hashData += hashData_last;
            let sign = hashData;
            return sign;
        },
        chooseUpload() {
            if(this.questionType == 2 || this.questionType == 3) {
                mui.toast('该功能不支持上传文件', {
                    duration: 'long',
                    type: 'div'
                })
                return
            }

            let filePathList = this.$refs.chooseDirRef.filePathList
            if(localStorage.getItem("showBtn") == 'true' && filePathList.length >= 2 && !this.isflageIOX ){
                this.$refs.chooseDirRef.showFilepath = true
            }else {
                this.uploadFunc()
            }
        },
        chooseDirUpload(item) {
            if(item&&(item.id != 0)) {
                let _that = this
                wx.invoke("ext_FileBrowser_AppointDirChooseFile", 
                    {data : {"appointDirPath": item.pathName}}, 
                    (res) => {
                        let channelId = "chat_upload_" + _that.createNonceStr(8) + new Date().getTime() + "";
                        console.log('res', res)
                        let recordArr = [{
                            name: res.name,
                            path: res.filePath,
                            fileSize: res.size
                        }]

                        let fileCount = recordArr.length + _that.uploadingFiles.length + _that.uploadFileList.length
                        if(fileCount > 5) {
                            mui.toast('最多上传5个文件', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        _that.uploadWord = true
                        
                        for(let i=0;i<recordArr.length;i++) {
                            let record = recordArr[i]
                            console.log("当前上传文件", record)
                            const suffix = record.name.split('.').reverse()[0]
                            if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase()) &&
                                !_that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                                mui.toast('目前只支持PDF、Word文件，请您核对后重新上传', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }
                            //多文件，文档和图片不可交叉上传
                            if(_that.validMultiFile(suffix, recordArr)) {
                                mui.toast('请分开上传文档和图片', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }
                            if(_that.uploadFileList && 0 < _that.uploadFileList.length) {
                                if(_that.validMultiFile(suffix, _that.uploadFileList)) {
                                    mui.toast('请分开上传文档和图片', {
                                        duration: 'long',
                                        type: 'div'
                                    })
                                    return
                                }
                            }
                            if(_that.picSuffixs.includes(suffix.toLocaleLowerCase()) && 1 < recordArr.length) {
                                mui.toast('图片只能上传一张', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }
                            if(_that.uploadFileList && 0 < _that.uploadFileList.length 
                                && _that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                                mui.toast('图片只能上传一张', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }

                            if (checkFileNameForSensitiveWords(record.name)) {
                                mui.toast('检测到敏感内容，请确认后再试。', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return false
                            }
                            if("doc" != suffix && "docx" != suffix) {
                                _that.uploadWord = false
                            }
                            _that.buttonShow = false
                            // _that.questionType = 1
                        }

                        for(let i=0;i<recordArr.length;i++) {
                            let record = recordArr[i]
                            channelId = "chat_upload_" + _that.createNonceStr(8) + new Date().getTime() + "";

                            _that.uploadingFiles.push({
                                path: record.path,
                                name: record.name,
                                id: channelId,
                                fileSize: record.fileSize
                            })
                        }
                        //没有上传定时任务，新建
                        console.log(_that.uploadTimer)
                        if(!_that.uploadTimer) {
                            _that.multiUpload()
                        }
                    })
            }else {
                this.uploadFunc()
            }
        },
        //上传文件
        uploadFunc() {
            // if(this.questionType == 2 || this.questionType == 3) {
            //     mui.toast('该功能不支持上传文件', {
            //         duration: 'long',
            //         type: 'div'
            //     })
            //     return
            // }
            let _that = this
            wx.invoke("ext_FileBrowser_StartPreView", {}, function (res) {
                let channelId = "chat_upload_" + _that.createNonceStr(8) + new Date().getTime() + "";

                console.log(res, 676767)
                if (_that.isflageIOX) {
                    // if (Number(res.size) / 40000000 > 1) {
                    //     mui.toast('上传文件大小不能大于40MB', {
                    //         duration: 'long',
                    //         type: 'div'
                    //     })
                    //     return
                    // }
                    let fileCount = _that.uploadFileList.length + 1
                    if(fileCount > 5) {
                        mui.toast('最多上传5个文件', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    const suffix = res.name.split('.').reverse()[0]
                    if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())
                        && !_that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('目前只支持PDF、Word文件，请您核对后重新上传', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    //多文件，文档和图片不可交叉上传
                    if(_that.validMultiFile(suffix,_that.uploadFileList)) {
                        mui.toast('请分开上传文档和图片', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if(_that.uploadFileList && 0 < _that.uploadFileList.length 
                        && _that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('图片只能上传一张', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }

                    if (checkFileNameForSensitiveWords(res.name)) {
                        mui.toast('检测到敏感内容，请确认后再试。', {
                            duration: 'long',
                            type: 'div'
                        })
                        return false
                    }
                    console.log("ios上传文件")
                    if("doc" == suffix || "docx" == suffix) {
                        _that.uploadWord = true
                    }else {
                        _that.uploadWord = false
                    }
                    _that.buttonShow = false
                    // _that.questionType = 1
                    $(".curtain").css("display", "block");
                    _that.checkList(res.filePath, res.name, channelId, res.size)
                } else {
                    let recordArr = JSON.parse(res.result)
                    let fileCount = recordArr.length + _that.uploadingFiles.length + _that.uploadFileList.length
                    if(fileCount > 5) {
                        mui.toast('最多上传5个文件', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    _that.uploadWord = true
                    for(let i=0;i<recordArr.length;i++) {
                        let record = recordArr[i]
                        console.log("当前上传文件", record)
                        const suffix = record.name.split('.').reverse()[0]
                        if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase()) &&
                            !_that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('目前只支持PDF、Word文件，请您核对后重新上传', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        //多文件，文档和图片不可交叉上传
                        if(_that.validMultiFile(suffix, recordArr)) {
                            mui.toast('请分开上传文档和图片', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        if(_that.uploadFileList && 0 < _that.uploadFileList.length) {
                            if(_that.validMultiFile(suffix, _that.uploadFileList)) {
                                mui.toast('请分开上传文档和图片', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }
                        }
                        if(_that.picSuffixs.includes(suffix.toLocaleLowerCase()) && 1 < recordArr.length) {
                            mui.toast('图片只能上传一张', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        if(_that.uploadFileList && 0 < _that.uploadFileList.length 
                            && _that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('图片只能上传一张', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }

                        if (checkFileNameForSensitiveWords(record.name)) {
                            mui.toast('检测到敏感内容，请确认后再试。', {
                                duration: 'long',
                                type: 'div'
                            })
                            return false
                        }
                        if("doc" != suffix && "docx" != suffix) {
                            _that.uploadWord = false
                        }
                        _that.buttonShow = false
                        // _that.questionType = 1
                    }

                    for(let i=0;i<recordArr.length;i++) {
                        let record = recordArr[i]
                        channelId = "chat_upload_" + _that.createNonceStr(8) + new Date().getTime() + "";

                        _that.uploadingFiles.push({
                            path: record.path,
                            name: record.name,
                            id: channelId,
                            fileSize: record.fileSize
                        })
                    }
                    //没有上传定时任务，新建
                    console.log(_that.uploadTimer)
                    if(!_that.uploadTimer) {
                        _that.multiUpload()
                    }
                }
            })
        },
        validMultiFile(suffix, validFileList) {
            //校验不通过，返回true
            return validFileList.some(file => {
                console.log('当前suffix', suffix)
                console.log('valid', file)
                const fileSuffix = file.name.split('.').reverse()[0]
                //同为文档
                let doc = this.fileSuffixs.includes(fileSuffix.toLocaleLowerCase()) && 
                this.fileSuffixs.includes(suffix.toLocaleLowerCase())
                //同为图片
                let pic = this.picSuffixs.includes(fileSuffix.toLocaleLowerCase()) && 
                    this.picSuffixs.includes(suffix.toLocaleLowerCase())
                if(doc || pic) {
                    //验证通过
                    return false
                }
                //验证不通过
                return true
            })
        },
        multiUpload() {
            $(".curtain").css("display", "block");
            this.uploadTimer = setInterval(() => {
                if(!this.uploadingFiles || this.uploadingFiles.length == 0) {
                    $(".curtain").css("display", "none");
                    this.uploadTimer = clearInterval(this.uploadTimer)
                }else if(!this.uploading) {
                    this.uploading = true
                    let file = this.uploadingFiles[0]
                    this.checkList(file.path, file.name, file.id, file.fileSize)
                }
            }, 100);
        },
        checkList(path, name, id, fileSize, hash, index) {
            let that = this
            that.disabledInp = true
            that.progressBar = true
            let iscp_port
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            let Authentication = sessionStorage.getItem("Authentication");
            const timestamp = new Date().getTime() + ""
            let userId = sessionStorage.getItem("userId");
            let sign = sm3(timestamp + "&" + userId)
            that.fileName = name
            wx.invoke("ext_Net_FragmentUpload", {
                data: {
                    serverAddress: localUrlLink + iscp_port + `/tjAiAssistant/storage/splitUpload2?channelId=${id}`,
                    filePath: path,
                    fragmentSize: that.CHUNK_SIZE,
                    fileName: name,
                    fileHash: hash ? hash : '',
                    upLoadFragmentIndex: index ? index : '',
                    channelId: id,
                    headerData: {
                        sign: sign,
                        userId: userId,
                        type: '',
                        timestamp: timestamp,
                        Authentication: Authentication,
                    }
                },
            }, function (res) {
                $(".curtain").css("display", "none");
                console.log("上传返回结果", res)
                if (res.err_msg.endsWith(":ok")) { //成功结果
                    //上传完成
                    // that.recording(id)
                    console.log("文件上传成功", name)
                    let wordType = 'WORD';
                    const suffix = name.split('.').reverse()[0]

                    if (that.wordSuffixs.includes(suffix.toLocaleLowerCase())) {
                    } else if (that.picSuffixs.includes(suffix.toLocaleLowerCase())) {
                        wordType = "IMG"
                        that.showImg = true
                    } else if (that.pdfSuffixs.includes(suffix.toLocaleLowerCase())) {
                        wordType = "PDF"
                    } else if (that.voiceSuffixs.includes(suffix.toLocaleLowerCase())) {
                        wordType = "VOICE"
                    }
                    let curUploadFile = {
                        id: id,
                        name: name,
                        type: wordType,
                        fileSize: that.calcFileSize(fileSize),
                        size: fileSize
                    } 
                    if("IMG" == wordType) {
                        that.imageToBase64(id, (imgSrc) => {
                            that.$set(curUploadFile, 'imgSrc', imgSrc)
                            that.uploadFileList.push(curUploadFile)
                        })
                    }else {
                        addPendingData(101, id)
                        that.uploadFileList.push(curUploadFile)
                    }

                    that.handleScrollBottom('uploadFileRef')
                    // that.uploadFile = {
                    //     id: id,
                    //     name: name,
                    //     type: wordType,
                    //     fileSize: that.calcFileSize(fileSize),
                    //     size: fileSize
                    // }
                    if (that.isflageIOX) {
                        $(".curtain").css("display", "none");
                    }
                    that.resetMainHeight()
                    //上传完成，下一个文件
                    that.uploadingFiles.shift()
                    that.uploading = false

                } else if (res.err_msg.endsWith(":cancel")) {
                    that.cleanData();
                    return
                } else {
                    //上传失败
                    if (that.myindex != Number(res.upLoadFragmentIndex)) {
                        that.myindex = Number(res.upLoadFragmentIndex);
                        that.retryNum = 0;
                    }
                    setTimeout(() => {
                        if (that.retryNum > 4) {
                            $(".curtain").css("display", "none");
                            // that.retryNum = 0
                            var btnArray = ["取消", "确定"];
                            var i = 0
                            mui.confirm(
                                "是否进行重试？",
                                "上传失败",
                                btnArray,
                                (e) => {
                                    if (i > 0) return
                                    i++
                                    if (e.index == 1) {
                                        that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                                    } else {
                                        that.cleanData()
                                    }
                                }
                            );
                        } else {
                            that.retryNum++

                            that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                        }

                    }, (that.retryNum + 1) * 1000)

                }
            })
        },
        calcFileSize(fileSize) {
            let kbf = (Math.floor((fileSize / 1024) * 100) / 100).toFixed(2);
            if (kbf > 1000) {
                //显示 MB
                return (Math.floor((fileSize / (1024 * 1024)) * 100) / 100).toFixed(2) + 'MB';
            }
            return kbf + 'KB';
        },
        cleanData() {
            this.disabledInp = false
            this.progressBar = false
            this.uploading = false
            this.uploadingFiles = []
        },
        //删除文件
        delFile(delFile) {
            // console.log('----删除文件----')
            if(delFile) {
                this.uploadFileList = this.uploadFileList.filter(item => item.id != delFile.id)
            }else {
                this.uploadFileList = []
            }
            this.resetMainHeight()
        },
        //开始录音
        startVoice() {

            this.voicing = true
            this.resetMainHeight()
            this.voiceTxt = {
                ind: '',
                old: ''
            }
            this.voiceTxt.ind = this.searchText
            this.getMeToken()

            // startLuyin(this, 'voiceInput', 'searchText')
        },
        //结束录音
        endVoice() {
            console.log('----结束录音----')
            this.voicing = false
            this.resetMainHeight()
            this.stopRecorder(1)
            var textarea = document.getElementById('voiceInput')
            textarea.blur()
            // endLuyin(this, 'voiceInput', 'searchText', this, () => {
            //     this.voicing = false
            //     this.resetMainHeight()
            // })
        },
        //-----------南瑞语音start-----------
        getMeToken() {
            let _that = this
            var iscp_port = ''
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            }
            userId = sessionStorage.getItem("userId");
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let timestamp = new Date().getTime() + ""
            let data = {
                "userId": userId,
                "timestamp": timestamp,
            }
            const datas = JSON.stringify(data)
            let sign = sm3(datas);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/soundRecording/thirdparty",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: datas,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    sign: sign,
                    Authentication: AuthenticationSession,
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                _that.WS_URL =
                                    `ws://127.0.0.1:${iscp_port}/websocket/asr/i?token=${res.resultValue}&capacityCode=${_that.CAPACITY_CODE}&language=${_that.LANG}&code=${_that.MODEL_CODE}&sessionId=${_that.VoiceItemID}`
                                if (!('WebSocket' in window)) {
                                    return
                                }
                                if (_that.count < 1) {
                                    wx.invoke("multiWindows_subscribe", { channelId: _that.VoiceItemID }, function (res) {
                                        console.log(res, "订阅返回结果")
                                        console.log(res.data.message, "信息")
                                        if (res.data.method == "onMessage String" && res.data.channelId == _that.VoiceItemID) {
                                            _that.onMessage(res)
                                        } else if (res.data.method == 'onReconnectFinishAndDisconn') {
                                            //重连失败处理
                                            _that.stopVB()
                                        }
                                    });
                                }
                                _that.count++
                                wx.invoke("ext_AudioRecorder_Start", {
                                    data: {
                                        channelId: _that.VoiceItemID,
                                        socketUrl: _that.WS_URL
                                    }
                                },
                                    function (res) {
                                        if (res.err_msg === 'ext_AudioRecorder_Start:ok') {
                                            //成功处理
                                            _that.checkClick = 1
                                            _that.checkSwitch = true
                                        }

                                        if (res.err_msg === 'ext_AudioRecorder_Start:fail') {
                                            //失败处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:cancel') {
                                            //取消处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:not_support ') {
                                        }
                                    })
                            }
                        } else {
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请求异常,请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            })
        },
        onOpen(evt, way, afterOpen) {
            let _that = this
            this.checkSwitch = true
            wx.startRecordVoiceBuffer({
                maxDuration: 100000000,
                sampleRate: 16000
            });
            wx.onRecordBufferReceived(function (res) {
                if (_that.isflageIOX) {
                    var a = ''
                    if (_that.bufferData.length == 26) {
                        _that.bufferData.forEach((item) => {
                            a += item
                            _that.bufferData = []
                        })
                        // _that.stopRecorder()
                        _that.doSend(a);
                    } else {
                        _that.bufferData.push(res.buffer)
                    }
                } else {

                    _that.doSend(res.buffer);
                }
            })
            if (!$(this).hasClass("stop")) {
                $(this).addClass("stop");
                let i = 0;
                $(this).data("interval", window.setInterval(function () {
                    $(".record-time").html((++i) + "s");
                }, 1000, i));
            }
        },
        doSend(message) {
            this.myWebsocket.readyState === 1 && this.myWebsocket.send(message);
        },
        onMessage(evt) {
            try {
                // const data = JSON.parse(evt.data);
                const data = JSON.parse(evt.data.message);
                console.log(evt.data,"内容")
                if (data.code == 200) {
                    // 这一行是赋值的
                    data.word = data.word.replace(/[|]/g, '\n')
                    data.word = data.word.replace(/[\n]/g, '\n\n')
                    this.insertContent(data)
                    // if (data.completed == true) {
                    //     this.voiceTxt.ind += data.word.length
                    //     this.voiceTxt.old = ''
                    //     this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt.ind)
                    //     setTimeout(() => {
                    //         this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt
                    //             .ind)
                    //     });
                    // }
                } else if (data.code == 'E000004') {
                    mui.toast("当前已达到最大并发量限制,请稍后再试", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                } else {
                    mui.toast(data.code + "语音服务异常", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                }
            } catch (error) {
                throw new Error('解析错误!' + error);
            }
        },
        insertContent(data) {
            let txt = data.word
            let ctxt = ''
            if(data.completed) {
                //完成
                this.voiceTxt.old += txt
                ctxt = this.voiceTxt.old
            }else{
                //未完成
                ctxt = this.voiceTxt.old + txt
            }
            this.voiceText = this.voiceTxt.ind + ctxt
            // this.searchText = this.voiceTxt.ind + ctxt

            // console.log("光标位置", this.searchText.length)

            // var textarea = document.getElementById('voiceInput')
            // textarea.setSelectionRange(this.searchText.length-1, this.searchText.length)
            // textarea.focus()

            // textarea.scrollLeft = textarea.scrollWidth
        },
        stopRecorder(num, callback) {
            let _this = this
            wx.invoke("ext_AudioRecorder_Stop", {
                data: {}
            },
                function (res) {
                    if (res.err_msg === 'ext_AudioRecorder_Stop:ok') {
                        if(!callback) {
                            _this.stopVB(num)
                        }
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:fail') {
                        //失败处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:cancel') {
                        //取消处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:not_support ') {
                        _this.stopVB(num)
                        wx.stopRecordVoiceBuffer({});
                        // if (_this.myWebsocket) {
                        _this.myWebsocket.close();
                    }
                    if(callback) {
                        callback()
                    }
                })
        },
        stopVB(num) {
            //成功处理
            this.time = clearInterval(this.time)
            // this.flag = true
            this.checkSwitch = false
            this.checkClick = 0
            $(this).removeClass("stop");
            window.clearInterval($(this).data("interval"));
            $(".record-time").html("");

            var textarea = document.getElementById('voiceInput')
            textarea.setSelectionRange(this.searchText.length, this.searchText.length)
            // textarea.focus()

            textarea.scrollLeft = textarea.scrollWidth
        },
        //-----------南瑞语音end-----------


        resetMainHeight() {
            //在nextTick的回调函数输出DOM信息
            this.$nextTick(() => {
                var fullHeight = document.querySelector('.main-container').offsetHeight
                var main = document.querySelector('.chat-main')
                var bottomHeight = document.querySelector('.bottom').offsetHeight
                main.style.height = (fullHeight - bottomHeight) + 'px'
            })
        },
        syncToInner(item) {
            console.log(item)
            if(item.answerAttach) {
                mySyncToInner('对话内容', "answerAttach="+item.answerAttach, 10, 1)
            }else {
                let content = item.reasoningContent ? (item.reasoningContent + item.content) : item.content
                mySyncToInner('对话内容', content, 10, 1)
            }
        },
        syncTripToInner(item) {
            console.log(item)
            mySyncToInner('对话内容', "answerTrip="+item.tripId+"_"+item.userId, 10, 1)
        },
        sendTripEmail(item) {
            console.log(item)
            mySendMail('对话内容', "answerTrip="+item.tripId+"_"+item.userId, 10, 1)
        },
        sendMyEmail(item) {
            console.log(item)
            if(item.answerAttach) {
                mySendMail('对话内容', "answerAttach="+item.answerAttach, 10, 1)
            }else {
                let content = item.reasoningContent ? (item.reasoningContent + item.content) : item.content
                mySendMail('对话内容', content, 10, 1)
            }
        },
        shareTripIgw(item) {
            shareIgw({
                sceneNo: '101',
                shareType: 2,
                content: item.tripId+"_"+item.userId
            })
        },
        shareIgw(item) {
            if(item.answerAttach) {
                shareIgw({
                    sceneNo: '101',
                    shareType: 1,
                    attchId: item.answerAttach
                })
            }else {
                let content = item.reasoningContent ? (item.reasoningContent + item.content) : item.content
                shareIgw({
                    sceneNo: '101',
                    shareType: 0,
                    content: content
                })
            }
        },
        preview(file) {
            myPreviewFile(file)
        },
        createNonceStr(len) {
            var e = len ? len : 16;
            var t =
                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
                a = t.length,
                n = "";
            for (i = 0; i < e; i++)
                n += t.charAt(Math.floor(Math.random() * a));
            return n;
        },
        handleBeforeUpload(files) {
            console.log("before", files)
        },
        handleAfterRead(files) {
            console.log("after", files)
            for(let i=0;i<files.length;i++) {
                let record = files[i]
                let channelId = "chat_upload_" + this.createNonceStr(8) + new Date().getTime() + "";

                this.uploadingFiles.push({
                    path: record.path,
                    name: record.name,
                    id: channelId,
                    fileSize: record.fileSize
                })
            }
            //没有上传定时任务，新建
            console.log(this.uploadTimer)
            if(!this.uploadTimer) {
                this.multiUpload()
            }
        },

        synthesis(item) {
            let userId = sessionStorage.getItem("userId");
            let Authentication = sessionStorage.getItem("Authentication");
            const timestamp = new Date().getTime() + "";
            let iscp_port;
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = "";
            }
            let content = item.content
            content = content.replace(/\n/g, "")
            let data = {
                text: content,
                nativeVoiceName: localStorage.getItem("nativeVoiceName") ? localStorage.getItem(
                    "nativeVoiceName") : "panting",
                timestamp: timestamp,
            };
            data = JSON.stringify(data)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/common/tts",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    sign: sign,
                    timestamp: timestamp,
                    userId: userId,
                    Authentication: Authentication,
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader(
                            "Authentication");
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                if (res.resultValue) {
                                    let voiceSign = sm3(timestamp + "&" + res.resultValue);

                                    let _audioSrc = localUrlLink + iscp_port + '/tjAiAssistant/common/download';
                                    _audioSrc += '?id=' + res.resultValue + '&userId=' + userId;
                                    _audioSrc += '&Authentication=' + Authentication + '&timestamp=' + timestamp + '&sign=' + voiceSign;

                                    // let _audioSrc = localUrlLink + iscp_port +
                                    //     `/tjAiAssistant/voice/getAudioByAttachmentId?Authentication=${Authentication}&id=${res.resultValue}&sign=${voiceSign}&timestamp=${timestamp}`
                                    // _audioSrc = './1.mp3'
                                    console.log('_audioSrc', _audioSrc)
                                    this.$set(item, 'audioSrc', _audioSrc)
                                    this.audioSrc = _audioSrc
                                    item.audioSrc = _audioSrc
                                    setTimeout(() => {
                                        this.clickFunc("play", item)
                                    },100)
                                }
                            }
                        } else {
                            // if (num == 1) return
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    } else {
                        // if (num == 1) return
                        mui.toast("完整性校验失败", {
                            duration: "long",
                            type: "div",
                        });
                    }
                },
                error: (e) => {
                    // if (num == 1) return
                    mui.toast("请求异常，请稍后再试！", {
                        duration: "long",
                        type: "div",
                    });
                },
            });

        },
        playFunc() {
            this.$emit('play', true)
        },
        // 暂停
        pauseFunc(e) {
            console.log()
            this.$emit('pause', false)
        },
        endedFunc(e) {
            if(this.audioItem) {
                this.$set(this.audioItem, 'isPlaying', false)
            }
        },
        clickFunc(val, item) {
            if(item) {
                this.audioItem = item
            }
            if (val == 'play') {
                if (!item.audioSrc) {
                    this.synthesis(item)
                    mui.toast("正在获取音频...", {
                        duration: "long",
                        type: "div",
                    });
                    return
                }
                this.audioSrc = item.audioSrc
                console.log(item.audioSrc, "item.audioSrc")
                this.$set(item, 'isPlaying', true)
                this.$refs.audio.play()
            } else if (val == 'pause') {
                if(item) {
                    this.$set(item, 'isPlaying', false)
                }
                if(this.$refs.audio) {
                    this.$refs.audio.pause()
                }
            }
        },

        //专业问答查询
        selectBtTypes() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/btType/selectAll",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        // console.log(res.resultValue);
                        this.majors = res.resultValue
                        // this.majors.push({
                        //     'typeCode': 'CodeSzh',
                        //     'typeName': '数字化',
                        //     'using': true
                        // });
                    }
                },
                error: (e) => {
                    console.log(e);
                },
            });
        },
        //专业问答重置
        typeReset() {
            const userId = sessionStorage.getItem("userId");
            let list = [{
                'id': '1',
                'typeCode': '',
                'typeName': '全部',
                'sn': 1,
                'using': true
            },
            {
                'id': '2',
                'typeCode': 'BZZD_001_002,BZZD_001_003,BZZD_001_004,BZZD_001_006,BZZD_002_001,BZZD_002_002,DXJY_001_001,WXCG_003_001,ZCFG_001_001,ZCFG_001_002,ZCFG_003_001,ZCFG_003_002',
                'typeName': '发展',
                'sn': 2,
                'using': true
            },
            {
                'id': '3',
                'typeCode': 'yxbk',
                'typeName': '营销',
                'sn': 3,
                'using': true
            },
            {
                'id': '4',
                'typeCode': 'CodeSzh',
                'typeName': '数字化',
                'sn': 4,
                'using': true
            },
            {
                'id': '5',
                'typeCode': 'CodeJiJian',
                'typeName': '基建',
                'sn': 5,
                'using': true
            },
            {
                'id': '6',
                'typeCode': 'CodeWuziRole',
                'typeName': '物资',
                'sn': 6,
                'using': true
            }, {
                'id': '7',
                'typeCode': 'CodeAuditNation,CodeAuditCompany',
                'typeName': '审计',
                'sn': 7,
                'using': true
            }, {
                'id': '8',
                'typeCode': 'CodeLaws',
                'typeName': '法律',
                'sn': 8,
                'using': true
            }]
            let param = {
                "list": JSON.stringify(list),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/btType/reset",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue);
                    }
                },
                error: (e) => {
                    console.log(e);
                },
            });
        },
        //专业问答更新
        updateBtTypes() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": 2,
                "using": false,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/btType/update",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue);
                    }
                },
                error: (e) => {
                    console.log(e);
                },
            });
        },
        //专业问答插入
        insertBtTypes() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": '5',
                "typeCode": "aa",
                "typeName": "aaa",
                "sn": 5,
                "using": false,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/btType/insert",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue);
                    }
                },
                error: (e) => {
                    console.log(e);
                },
            });
        },
        //专业问答删除
        deleteBtTypes() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": '5',
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/btType/deleteBtType",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue);
                    }
                },
                error: (e) => {
                    console.log(e);
                },
            });
        },
        handleDeepSeekSelect(item) {
            this.showDeepSeekPop = false
            if('close' == item.value) {
                //选中取消
                this.cancelChatQtype()
            }else {
                this.deepSeekActions.forEach(da => {
                    if(da.name == item.name) {
                        da.color = this.deepSeekColor
                        if(!item.unsave) {
                            this.uploadFileList = []
                            this.configChatQtype(da.value)
                        }
                        this.deepSeekItem = item
                    }else {
                        da.color = ''
                    }
                })
            }
        },
        queryChatQtype() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "questionType": 4,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chatQtype/queryChatQtype",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            let data = res.resultValue
                            this.questionType = 4
                            this.deepSeekActions = this.defaultModelActions
                            if(data) {
                                this.deepSeekActions.forEach(item => {
                                    if(item.value == data.subType && 'BAIDU' != item.value && 'ALI' != item.value) {
                                        item.color = this.deepSeekColor
                                        this.deepSeekItem = item
                                    }
                                })
                            }
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        configChatQtype(subType) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "questionType": 4,
                "subType": subType,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chatQtype/configChatQtype",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            let data = res.resultValue
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        cancelChatQtype() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "questionType": 4,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/chatQtype/cancelChatQtype",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            this.queryChatQtype()
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        handleChangeThinkShow(item) {
            this.$set(item, 'thinkShow', !item.thinkShow)
        },
        getModelIcon() {
            if(!this.deepSeekItem) {
                return 
            }
        },
        splitModelName(name) {
            if('通用对话V3' == name) {
                return ['通', '用', '对', '话', 'V3']
            }else{
                return name.split('')
            }
        },
        handleEditTrip(item) {
            this.$set(item, 'editable', true)
            this.oldTrips = JSON.parse(JSON.stringify(item.trips))
        },
        handleCancelEditTrip(item) {
            this.$set(item, 'editable', false)
            this.$set(item, 'trips', this.oldTrips)
        },
        showTimePicker(item, trip, index){
            if(!item.editable) {
                return
            }
            this.selDate = new Date()
            this.currentTrip = trip
            this.minDate = new Date()
            let now = new Date()
            now.setFullYear(now.getFullYear() + 2)
            this.maxDate = now; 
            let date = new Date(trip.tripTime)
            this.selDate = date
            this.pickerKey += 1; // 每次打开时改变key值强制重新渲染
            this.showTimeFlag = true;
        },
        confirmDate(value){
            this.showTimeFlag = false
            if(this.selDate){
                this.$set(this.currentTrip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', this.selDate))
                //如果当天，显示今天 hh:mm
                if(dateFormat('yyyy-MM-dd', this.selDate) == dateFormat('yyyy-MM-dd', new Date())) {
                    this.$set(this.currentTrip, 'tripTimeShow', dateFormat('今天 hh:mm', this.selDate))
                }else{
                    this.$set(this.currentTrip, 'tripTimeShow', dateFormat('yyyy-MM-dd hh:mm', this.selDate))
                }
            }
        },
        cancelDate(){
            this.showTimeFlag = false
            this.selDate = null;
        },
        formatTime(date) {
            return dateFormat('yyyy年MM月dd日 hh:mm', date)
        },
        timerFormatter(type, val) {
            if (type === 'year') {
              return val + '年';
            }
            if (type === 'month') {
              return val + '月';
            }
            if (type === 'day') {
              return val + '日';
            }
            if (type === 'hour') {
                return val + '时';
            }
            if (type === 'minute') {
                return val + '分';
            }
            return val;
        },
        handleUpdateTrip(item) {
            this.handleTripConfirm(item, {
                "chatRecordId": item.id,
                "trips": item.trips,
            }, () => {
                this.$set(item, 'tripStatus', 0)
                this.$set(item, 'trips', [])
                this.searchText = "修改日程"
                this.send({
                    'chatIntent': 'tripRemind',
                    'tripChatRecordId': item.id
                })
            })
        },
        handleTripConfirm(item, extParam, callback) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                ...extParam,
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            }
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/trip/updateTrip",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            
                            this.$set(item, 'editable', false)
                            
                            if(callback) {
                                callback()
                            }else {
                                mui.toast('日程信息修改成功', {
                                    duration: 1000,
                                    type: 'div'
                                })
                            }
                        }else {
                            mui.toast('日程信息修改失败', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        handleTripDelete(item) {
            const ids = item.trips.filter(trip => trip.check).map(trip => trip.id)
            if(null == ids || 0 == ids.length) {
                mui.toast('请先选择日程', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }

            mui.confirm("是否删除日程", "删除日程", ["取消", "确定"], (e) => {
                if (e.index == 1) {
                    this.deleteTrip(ids.join(), item.id, () => {
                        let newTrips = item.trips.filter(trip => !trip.check);

                        if(!newTrips || 0 == newTrips.length) {
                            newTrips = null
                        }
                        this.$set(item, 'trips', newTrips)
                        this.$set(item, 'editable', false)
                    })
                } else {
                }
            });
        },
        deleteTrip(ids, recordId, callback) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "chatRecordId": recordId,
                "userId": userId,
                "tripIds": ids,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/trip/deleteTrip",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            
                            if(callback) {
                                callback()
                            }

                            mui.toast('日程信息删除成功', {
                                duration: 1000,
                                type: 'div'
                            })
                        }else {
                            mui.toast('日程信息删除失败', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        handleChangeRemindStatus(value) {
            if(!value) {
                this.$refs.remindTimeCb.forEach(item => {
                    item.toggle(false);
                })
                this.remindTimeList.forEach(item => {
                    this.$set(item, 'disabled', true)
                })
            }else {
                this.remindTimeList.forEach(item => {
                    this.$set(item, 'disabled', false)
                })
            }
        },
        handleSetRemindTime(trip, index) {
            this.showRemindTimePop = true
            this.remindTimes = []
            this.currentTrip = trip
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "id": trip.id,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/trip/getTripRemindTime",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            
                            this.$nextTick(() => {
                                let data = res.resultValue
                                this.remindTimeCheck = 1 == data.remindStatus
                                let tripReminds = data.tripReminds
                                if(0 == this.remindTimeCheck) {
                                    this.remindTimeList.forEach(item => {
                                        this.$set(item, 'disabled', true)
                                    })
                                }else if(tripReminds && 0 < tripReminds.length) {
                                    tripReminds.forEach(tripRemind => {
                                        this.$refs.remindTimeCb[tripRemind.remindCode].toggle(true)
                                    })
                                }else {
                                    this.$refs.remindTimeCb[2].toggle(true)
                                }
                            })
                        }else {
                            mui.toast('获取日程提醒时间失败', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        closeRemindTimePop() {
            console.log(this.remindTimes)
            const remindCodes = this.remindTimes.map(item => item.id)
            this.showRemindTimePop = false
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "id": this.currentTrip.id,
                "remindStatus": this.remindTimeCheck ? 1 : 0,
                "remindCodes": remindCodes.join(),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/trip/setTripRemindTime",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            
                            mui.toast('提醒时间设置完成', {
                                duration: 1000,
                                type: 'div'
                            })
                        }else {
                            mui.toast('提醒时间设置失败', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        toggleRemind(index, checkItem) {
            if(!checkItem.disabled){
                this.$refs.remindTimeCb[index].toggle()
            }
        },
        //新增冲突日程
        handleAddTrip(item) {
            this.searchText = "添加日程"
            this.$set(item, 'tripStatus', 0)
            this.send({
                'chatIntent': 'tripRemind',
                'tripChatRecordId': item.id
            })
        },
        //取消新增日程
        handleCancelTrip(item) {
            this.searchText = "取消日程"
            this.$set(item, 'tripStatus', 0)
            this.send({
                'chatIntent': 'tripRemind',
                'tripChatRecordId': item.id
            })
        },
        showAllTripPop() {
            this.tripListPop = true
            this.getAllTrips()
        },
        getAllTrips() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/trip/getAllTripsByUser",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            
                            this.allTrips = res.resultValue
                            this.allTripsLength = this.allTrips.length || 0
                            let index = 0
                            this.allTrips.forEach(groupTrips => {
                                groupTrips.forEach(trip => {
                                    this.$set(trip, 'index', index++)
                                    this.$set(trip, 'tripTime', dateFormat('yyyy-MM-dd hh:mm', trip.tripTime))
                                    this.$set(trip, 'groupTime', dateFormat('M月d日 星期w', trip.tripTime))
                                })
                            })
                        }else {
                            mui.toast('日程获取失败', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('日程获取失败', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        closeTripListPop() {
            this.tripListPop = false
            this.multiChoose = false
            this.chooseAll = false
            this.checkTripList = []
            this.openHistoryRecord(this.currentChatId)
        },
        chooseTripAllClick(event) {
            if(this.chooseAll) {
                this.$refs.checkboxes.forEach(item => {
                    item.toggle(true);
                })
            }else {
                this.$refs.checkboxes.forEach(item => {
                    item.toggle(false);
                })
            }
        },
        toggleTrip(checkItem) {
            if(!this.multiChoose) {
                return
            }
            const exist = this.checkTripList.some(item => item.id === checkItem.id)
            if(!exist) {
                //选中,且全部选中
                if(this.checkTripList.length + 1 == this.allTripsLength) {
                    this.chooseAll = true
                }
            }else {
                this.chooseAll = false
            }
            this.$refs.checkboxes[checkItem.index].toggle()
        },
        handleMultiChooseClick() {
            if(!this.allTrips || 0 == this.allTrips.length) {
                return
            }
            this.multiChoose = true
        },
        handleMultiChooseShow() {
            this.multiChoose = false
            this.chooseAll = false
            this.checkTripList = []
        },
        handlePopTripDelete() {
            if(null == this.checkTripList || 0 == this.checkTripList.length) {
                mui.toast('请先选择日程', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }

            mui.confirm("是否删除日程", "删除日程", ["取消", "确定"], (e) => {
                if (e.index == 1) {
                    let ids = this.checkTripList.map(item => item.id).join(',')
                    this.deleteTrip(ids, null, () => {
                        this.multiChoose = false
                        this.chooseAll = false
                        this.getAllTrips()
                    })
                } else {
                }
            });
        },
        handleCreateTrip(item) {
            this.handleTripConfirm(item, {
                "chatRecordId": item.id,
                "tmpTrips": item.trips,
            }, () => {
                this.searchText = "创建日程"
                this.send({
                    'chatIntent': 'tripRemind',
                    'tripChatRecordId': item.id
                })
            })
        },
        handleAllTripChat() {
            this.handleCancleTripTool()
            this.searchText = "查看全部提醒"
            this.send({
                'chatIntent': 'tripRemind',
            })
        },
        showErrMsg(errMsg) {
            let contents = errMsg.split("\n")
            let html = contents.map(content => '<p>' + content + '</p>').join('')
            return html
        },
        haveTripPermission() {
            return havePermissions('12', '12-trip')
        },
        handleCancleTripTool() {
            this.inputPlaceholder = '请在此输入文字'
            this.searchText = ''
            this.showTripTool = false
        },
        handleCloseTripTool() {
            this.questionType = 1
            this.deepSeekActions = this.defaultModelActions
            this.handleCancleTripTool()
        },
        handleReset() {
            this.deepSeekActions = this.defaultModelActions
            this.handleCancleTripTool()
        },
        //开始录音
        startTalk() {
            this.stopRecorder(null, () => {
                console.log('startTalk')
            })
            this.voiceTxt = {
                ind: '',
                old: ''
            }
            this.voiceTxt.ind = this.voiceText
            this.getMeToken()
        },
        //停止录音
        stopTalk() {
            // this.stopTalkCallBack()
            this.stopRecorder()
        },
        stopTalkCallBack() {
            var textarea = document.getElementById('voiceInput')
            textarea.setSelectionRange(this.searchText.length-1, this.searchText.length)
            textarea.focus()

            textarea.scrollLeft = textarea.scrollWidth
        },
        toggleVoiceKeybord(e) {
            this.voicing = !this.voicing
            e.preventDefault()
            e.stopPropagation();
        },
        handleVoiceTouchStart(e) {
            this.startY = e.touches[0].clientY
            this.isPressing = true
            
            // 开始长按计时
            this.pressTimer = setTimeout(() => {
                // 这里可以添加开始录音的逻辑
                console.log('开始录音...')
                this.startTalk()
            }, 500) // 500ms 视为长按
        },
        handleVoiceTouchEnd() {
            clearTimeout(this.pressTimer)
            
            if (!this.isPressing) return
            
            // 判断是否上滑取消
            const moveDistance = 0===this.moveY ? 0 : (this.moveY - this.startY)
            if (moveDistance < -30) { // 上滑超过30px视为取消
                console.log('取消发送')
                setTimeout(() => {
                    this.stopRecorder(null, () => {
                        this.voiceText = ''
                        this.voicing = false
                        this.isPressing = false
                        this.buttonText = '松手发送，上移取消'
                        this.movingUp = false
                        this.moveY = 0
                    })
                }, 1000)
            } else {
                // 正常松开发送
                console.log('发送消息')
                setTimeout(() => {
                    this.stopRecorder(null, () => {
                        this.searchText = this.voiceText
                        this.voicing = false
                        this.isPressing = false
                        this.buttonText = '松手发送，上移取消'
                        this.movingUp = false
                        this.moveY = 0
                    })
                }, 1000)
            }
            
            // this.voicing = false
            // this.isPressing = false
            // this.buttonText = '松手发送，上移取消'
            // this.movingUp = false
            // this.moveY = 0
        },
        handleVoiceTouchMove(e) {
            if (!this.isPressing) return
            
            this.moveY = e.touches[0].clientY
            const moveDistance = this.moveY - this.startY
            
            if (moveDistance < -30) { // 上滑超过30px
                this.buttonText = '松手取消'
                this.movingUp = true
            } else {
                this.buttonText = '松手发送，上移取消'
                this.movingUp = false
            }
        }
    }
});
